using ButcherFactory.BO.Utils;
using Forks.EnterpriseServices.DomainObjects2;
using Forks.EnterpriseServices.DomainObjects2.DQuery;
using Forks.EnterpriseServices.SqlDoms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ButcherFactory.BO.LocalBL
{
  public static class BaseInfoBL
  {
    public static List<T> GetList<T>(int range = 10, params string[] extendFields)
      where T : BaseInfo, new()
    {
      var query = new DQueryDom(new JoinAlias(typeof(T)));
      query.Columns.Add(DQSelectColumn.Field("ID"));
      query.Columns.Add(DQSelectColumn.Field("Name"));
      foreach (var field in extendFields)
        query.Columns.Add(DQSelectColumn.Field(field));
      query.OrderBy.Expressions.Add(DQOrderByExpression.Create("ID", true));
      query.Range = SelectRange.Top(range);
      var result = new List<T>();
      var type = typeof(T);
      using (var session = DmoSession.New())
      {
        using (var reader = session.ExecuteReader(query))
        {
          while (reader.Read())
          {
            var entity = new T();
            result.Add(entity);
            entity.ID = (long)reader[0];
            entity.Name = (string)reader[1];
            var idx = 2;
            foreach (var field in extendFields)
            {
              type.GetProperty(field).SetValue(entity, reader[idx]);
              idx++;
            }
          }
        }
      }
      return result;
    }
  }
}
