using Newtonsoft.Json.Linq;

using Sqler.Module.Sqler.Logical.DataEditor.GridManage;

using Vit.AutoTemp;
using Vit.AutoTemp.Repository;
using Vit.Core.Module.Serialization;
using Vit.Core.Util.Common;
using Vit.Core.Util.ComponentModel.Data;
using Vit.Core.Util.ComponentModel.SsError;
using Vit.Linq;
using Vit.Linq.ComponentModel;
using Vit.Linq.FilterRules.ComponentModel;

using Model = App.Module.Sqler.Logical.DataEditor.GridManage.AutoTempModel_Grid;

namespace App.Module.Sqler.Logical.DataEditor.GridManage
{
    public class GridManageRepository : IRepository<Model>
    {
        public RespositoryDataProvider<Model> ToDataProvider()
        {
            var str = File.ReadAllText(CommonHelp.GetAbsPath("Sqler_DataEditor_schema.ControllerConfig.json"));
            var controllerConfig = Json.Deserialize<AutoTempControllerConfig>(str);
            return new RespositoryDataProvider<Model>(this, templateName, controllerConfig);
        }

        const string templateName = "Sqler_DataEditor_schema";


        IQueryable<Model> dataSource => GridService.models.AsQueryable();

        public ApiReturn<Model> GetModel(string id)
        {
            var model = dataSource.FirstOrDefault(m => m.id == id);
            return model;
        }

        public ApiReturn<Model> Insert(Model model)
        {
            var model_ = GridService.Upsert(model,null);
            DataEditorHelp.Init();
            return model_;
        }

        public ApiReturn<Model> Update(Model model, string id)
        {
            var model_ = GridService.Upsert(model,id);

            if (model_ != null)
            {
                DataEditorHelp.Init();
                return model_;
            }
            else
            {
                return new SsError { errorMessage = "待修改的数据不存在" };
            }
        }

        public ApiReturn Delete(Model model)
        {
            if (GridService.Delete(model))
            {
                DataEditorHelp.Init();
                return true;
            }
            else
            {
                return new SsError { errorMessage = "待删除的数据不存在" };
            }
        }


        public ApiReturn<PageData<Model>> GetList(FilterRule filter, IEnumerable<OrderField> sort, PageInfo page)
        {
            var query = dataSource.AsQueryable();

            var pageData = query.ToPageData(filter, sort, page);

            // _childrenCount
            pageData.items.ForEach(m =>
            {
                m._childrenCount = query.Count(child => child.pid == m.id);
            });

            return new ApiReturn<PageData<Model>> { data = pageData };
        }



    }
}
