using Fluid;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Test.Template;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

partial class Program
{
    static void Main()
    {
        //发布的目录和项目的目录有区别的  
        var rootPath = AppContext.BaseDirectory.Replace(@"\bin\net8.0\", "").Replace(@"\bin\Release\net8.0\", "");

        var templateFolderPath = Path.Combine(rootPath, "Template");
        var outPutTemplateFolderPath = Path.Combine(rootPath, "TemplateOutPut");

        #region 生成文件目录准备
        if (!Directory.Exists(outPutTemplateFolderPath))
        {
            Directory.CreateDirectory(outPutTemplateFolderPath);
        }
        var servicePath = Path.Combine(outPutTemplateFolderPath, "Service");
        var iServicePath = Path.Combine(outPutTemplateFolderPath, "IService");
        var entityPath = Path.Combine(outPutTemplateFolderPath, "Entity");
        var dtoPath = Path.Combine(outPutTemplateFolderPath, "DTO");

        if (!Directory.Exists(servicePath))
        {
            Directory.CreateDirectory(servicePath);
        }
        if (!Directory.Exists(iServicePath))
        {
            Directory.CreateDirectory(iServicePath);
        }
        if (!Directory.Exists(entityPath))
        {
            Directory.CreateDirectory(entityPath);
        }
        if (!Directory.Exists(dtoPath))
        {
            Directory.CreateDirectory(dtoPath);
        }
        #endregion


        #region 直接通过上下文拿到实体信息


        var contextOptions = new DbContextOptionsBuilder<IRaCISDBContext>().UseSqlServer(@"Server=106.14.89.110,1435;Database=Test_IRC;User ID=sa;Password=xc@123456;TrustServerCertificate=true").Options;

        using var dbContext = new IRaCISDBContext(contextOptions);

        var dbModel = dbContext.Model;

        foreach (var entityType in dbModel.GetEntityTypes())
        {
            string tableName = entityType.GetTableName();
            Console.WriteLine($"Table: {tableName}");

            foreach (var property in entityType.GetProperties())
            {
                string columnName = property.GetColumnName();
                string dataType = property.ClrType.Name;
                bool isNullable = property.IsNullable;

                Console.WriteLine($"    Column: {columnName}, Data Type: {dataType}, Is Nullable: {isNullable}");
            }
        }
        #endregion


        // 要生成的表名数组
        var tableNames = new List<string> { "Product"/*, "Order"*/ };

        try
        {
            //便利所有模板文件进行生成操作
            foreach (var templateFilePath in Directory.GetFiles(templateFolderPath))
            {

                var fileName = Path.GetFileNameWithoutExtension(templateFilePath);

                //模板放入具体的文件夹
                //var folder = fileName == "Entity" ? "Entity" : fileName.Replace("Entity", "");

                foreach (var tableName in tableNames)
                {
                    var model = new TemplateModel
                    {
                        TableName = tableName,

                        IsPaged = true
                    };


                    var parser = new FluidParser();

                    var source = File.ReadAllText(templateFilePath);

                    if (parser.TryParse(source, out var template, out var error))
                    {
                        var context = new TemplateContext(model);

                        //Console.WriteLine(template.Render(context));

                        string outputFilePath = Path.Combine(outPutTemplateFolderPath, /*folder,*/ $"{fileName.Replace("Entity", tableName)}.cs");

                        File.WriteAllText(outputFilePath, template.Render(context));
                    }
                    else
                    {
                        Console.WriteLine($"Error: {error}");
                    }



                }
            }
        }
        catch (Exception ex)
        {

            Console.WriteLine($"Error: {ex.Message}");
        }


    }

    // Model class to pass data to the template
    public class TemplateModel
    {
        public string TableName { get; set; }

        //生成的列表是是分页 还是不分页
        public bool IsPaged { get; set; }

        // 列表视图模型名称
        public string TableNameView => TableName + "View";
        //列表查询模型名称
        public string TableNameQuery => TableName + "Query";
        //添加和编辑模型名称
        public string TableNameAddOrEdit => TableName + "AddOrEdit";
        //删除主键属性名
        public string LowercaseTableNameId => char.ToLower(TableName[0]) + TableName.Substring(1) + "Id";

        public string LowercaseRepositoryName => $"_{char.ToLower(TableName[0]) + TableName.Substring(1)}Repository";

        public string LowercaseQueryableName => $"{char.ToLower(TableName[0]) + TableName.Substring(1)}Queryable";

        public DateTime DateTimeNow = DateTime.Now;
    }
}