using System.ComponentModel.DataAnnotations;


using Vit.AutoTemp.Repository;
using Vit.Core.Util.ComponentModel.Data;
using Vit.Core.Util.ConfigurationManager;
using Vit.Linq;
using Vit.Linq.ComponentModel;
using Vit.Linq.FilterRules.ComponentModel;

namespace App.Module.Sqler.Logical.SqlVersion
{

    #region SqlVersionModuleRepository
    public class ModuleRepository : IRepository<SqlVersionModuleModel>
    {

        public static List<string> GetAllModules()
        {
            DirectoryInfo dir = new DirectoryInfo(SqlerHelp.GetDataFilePath("SqlVersion"));
            if (dir.Exists)
            {
                return dir.GetFiles("*.json").Select(file => Path.GetFileNameWithoutExtension(file.Name)).ToList();
            }

            return new();
        }

        public SqlCode_DataProvider[] sqlCode_DataProviders { get; private set; }
        readonly SqlVersionModuleModel[] moduleModels;
        public ModuleRepository()
        {
            sqlCode_DataProviders = GetAllModules()
                    .Select(moduleName => new SqlCode_DataProvider("Sqler_SqlVersion_Module_" + moduleName, moduleName))
                   .ToArray();


            moduleModels = sqlCode_DataProviders.AsQueryable()
                    .Select(dataProvider => new SqlVersionModuleModel(dataProvider)).ToArray();


        }


        public ApiReturn Delete(SqlVersionModuleModel m)
        {
            File.Delete(SqlerHelp.GetDataFilePath("SqlVersion", m.module + ".json"));
            SqlVersionHelp.InitEnvironmentAndAutoTemp();
            return true;
        }

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

            return query.ToPageData(filter, sort, page);
        }

        public ApiReturn<SqlVersionModuleModel> GetModel(string id)
        {
            var query = moduleModels.AsQueryable();

            return query.FirstOrDefault(m => m.module == id);
        }

        public ApiReturn<SqlVersionModuleModel> Insert(SqlVersionModuleModel m)
        {
            var fileName = m.module + ".json";
            var filePath = SqlerHelp.GetDataFilePath("SqlVersion", fileName);
            System.IO.File.WriteAllText(filePath,"[]");

            SqlVersionHelp.InitEnvironmentAndAutoTemp();
            return m;
        }

        public ApiReturn<SqlVersionModuleModel> Update(SqlVersionModuleModel m, string id)
        {
            var query = moduleModels.AsQueryable();

            var mFromDb = query.FirstOrDefault(m_ => m_.module == m.module);


            FileInfo fi = new FileInfo(SqlerHelp.GetDataFilePath("SqlVersion", mFromDb.module + ".json"));
            fi.MoveTo(SqlerHelp.GetDataFilePath("SqlVersion", m.module + ".json"));

            SqlVersionHelp.InitEnvironmentAndAutoTemp();
            return m;
        }



    }
    #endregion


    #region Model
    public class SqlVersionModuleModel
    {
        public SqlVersionModuleModel()
        {
        }

        public SqlVersionModuleModel(SqlCode_DataProvider dataProvider)
        {
            this.dataProvider = dataProvider;
            id = dataProvider.module;
            module = dataProvider.module;
            template = dataProvider.template;
        }

        /// <summary>
        /// [[AutoTemp_Field:Ignore]] 
        /// </summary>
        [System.Text.Json.Serialization.JsonIgnore]
        [Newtonsoft.Json.JsonIgnore]
        public SqlCode_DataProvider dataProvider { get; private set; }

        /// <summary>
        /// [[AutoTemp: { 
        ///     "permit": { "update":false, "delete":false, "show":false},
        ///     "listConfig": {
        ///         "listButtons": [
        ///             {
        ///                 "title": "一键升级",
        ///                 "jsHandler": "(sender)=>{ window.open('/sqler/SqlVersion/oneKeyUpgrade'); }"
        ///             }
        ///         ],
        ///         "rowButtons": [
        ///             {
        ///                 "title": "管理",
        ///                 "jsHandler": "(sender,id,row)=>{ theme.addTab('/Scripts/autoTemp/list.html?template='+row.template,'SqlVersion_'+row.module); }" 
        ///             },
        ///             {
        ///                 "title": "升级至最新",
        ///                 "jsHandler": "(sender,id,row)=>{ window.open('/sqler/SqlVersion/upgrade?version=-1&amp;template='+row.template); }" 
        ///             },
        ///             {
        ///                 "title": "下载sql",
        ///                 "jsHandler": "(sender,id,row)=>{ window.open('/sqler/SqlVersion/download?template='+row.template); }" 
        ///             }
        ///         ]
        ///     }
        /// } ]]
        /// 
        /// [[AutoTemp_Field: {   "editable":false,"visible":false  } ]]
        /// 
        /// </summary>
        [Key]
        public string id { get; set; }


        public string module { get; set; }

        /// <summary>
        /// [[AutoTemp_Field: {   "visible":false  } ]]
        /// </summary>
        public string template { get; set; }


        /// <summary>
        /// 最高版本
        /// [[AutoTemp_Field: {   "editable":false  } ]]
        /// </summary>
        public int lastVersion { get => dataProvider?.lastVersion ?? -1; }


        /// <summary>
        /// 当前版本
        /// [[AutoTemp_Field: {   "editable":false  } ]]
        /// </summary>
        public int? curDbVersion { get => SqlVersionService.GetDbCurVersion(dataProvider?.module); }

    }

    #endregion


}
