using Forks.EnterpriseServices.DomainObjects2;
using Forks.Utils;
using Forks.Utils.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ButcherFactory.BO.Utils
{
  public static class DbUtil
  {
    public static void UpdateDatabase(string sqlConnection)
    {
      using (ISqlUtil sqlUtil = new SqlUtil(sqlConnection))
      {
        var boTypes = GetTypes();
        Dmo.UpdateTables(sqlUtil, boTypes);
      }
    }

    static IEnumerable<Type> GetTypes()
    {
      var asm = Assembly.GetAssembly(typeof(Worker));
      foreach (var t in asm.GetExportedTypes())
      {
        if (t.IsAbstract)
        {
          continue;
        }
        if (t.IsClass && IsMapTable(t))
        {
          yield return t;
        }
      }
    }

    static bool IsMapTable(Type t)
    {
      var attr = ReflectionUtil.GetAttribute<MapToTableAttribute>(t);
      if (attr == null)
      {
        return false;
      }
      return true;
    }
  }
}
