using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace IRaCIS.Core.Application.Helper;

public static class InternationalizationHelper
{
    public static string JsonFileFolder = Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources);

    public static FileSystemWatcher FileSystemWatcher_US { get; set; }
    public static FileSystemWatcher FileSystemWatcher_CN { get; set; }

    private static void VerifyFolder()
    {
        if (!Directory.Exists(JsonFileFolder) ||
           !Directory.GetFiles(JsonFileFolder).Any(filePath => Path.GetExtension(filePath).Equals(".json", StringComparison.OrdinalIgnoreCase)))
        {
            throw new BusinessValidationFailedException("国际化Json文件目录有误");
        }
    }

    public static async Task BatchAddJsonKeyValueAsync(List<BatchAddInternationalizationDto> batchAddDtos)
    {
        VerifyFolder();

        var usJsonPath = Path.Combine(JsonFileFolder, StaticData.En_US_Json);
        var cnJsonPath = Path.Combine(JsonFileFolder, StaticData.Zh_CN_Json);


        //更新json 文件  同时更新内存缓存的数据
        foreach (var filePath in new string[] { usJsonPath, cnJsonPath })
        {
            var json = await File.ReadAllTextAsync(filePath);

            JObject jsonObject = JObject.Parse(json, new JsonLoadSettings() { CommentHandling = CommentHandling.Load });

            // 添加或更新指定的键值对

            if (filePath.Contains(StaticData.En_US_Json))
            {
                foreach (var item in batchAddDtos)
                {
                    jsonObject[item.Code] = item.Value;

                    StaticData.En_US_Dic[item.Code] = item.Value;

                    //日志记录该信息方便自己人看， 返回给客户的是配置的
                    StaticData.Log_Locoalize_Dic[item.Code] = item.Description;
                }
            }
            else
            {
                foreach (var item in batchAddDtos)
                {
                    jsonObject[item.Code] = item.Value;

                    StaticData.Zh_CN_Dic[item.Code] = item.Value;
                }
            }


            await File.WriteAllTextAsync(filePath, jsonObject.ToString());

        }
    }

    public static async Task AddOrUpdateJsonKeyValueAsync(string key, string value, string valueCN, string description)
    {

        VerifyFolder();

        var usJsonPath = Path.Combine(JsonFileFolder, StaticData.En_US_Json);
        var cnJsonPath = Path.Combine(JsonFileFolder, StaticData.Zh_CN_Json);


        //更新json 文件  同时更新内存缓存的数据
        foreach (var filePath in new string[] { usJsonPath, cnJsonPath })
        {
            var json = await File.ReadAllTextAsync(filePath);

            JObject jsonObject = JObject.Parse(json, new JsonLoadSettings() { CommentHandling = CommentHandling.Load });

            // 添加或更新指定的键值对

            if (filePath.Contains(StaticData.En_US_Json))
            {
                jsonObject[key] = value;

                StaticData.En_US_Dic[key] = value;

                //日志记录该信息方便自己人看， 返回给客户的是配置的
                StaticData.Log_Locoalize_Dic[key] = description;
            }
            else
            {
                jsonObject[key] = valueCN;

                StaticData.Zh_CN_Dic[key] = valueCN;
            }


            await File.WriteAllTextAsync(filePath, jsonObject.ToString());

        }

    }


    public static async Task InitInternationlizationDataAndWatchJsonFileAsync(IRepository<Internationalization> _internationalizationRepository)
    {
        //查询数据库的数据
        var toJsonList = await _internationalizationRepository.Where(t => t.InternationalizationType == 1).Select(t => new
        {
            t.Code,
            t.Value,
            t.ValueCN,
            t.Description
        }).ToListAsync();

        //组织成json 文件

        var usJsonPath = Path.Combine(JsonFileFolder, StaticData.En_US_Json);
        var cnJsonPath = Path.Combine(JsonFileFolder, StaticData.Zh_CN_Json);


        //本地静态文件国际化需要
        foreach (var tojsonItem in toJsonList)
        {
            StaticData.En_US_Dic[tojsonItem.Code] = tojsonItem.Value;
            StaticData.Zh_CN_Dic[tojsonItem.Code] = tojsonItem.ValueCN;

            //日志记录该信息方便自己人看， 返回给客户的是配置的
            StaticData.Log_Locoalize_Dic[tojsonItem.Code] = tojsonItem.Description;
        }

        File.WriteAllText(usJsonPath, JsonConvert.SerializeObject(StaticData.En_US_Dic));
        File.WriteAllText(cnJsonPath, JsonConvert.SerializeObject(StaticData.Zh_CN_Dic));


        //监测Json文件变更 实时刷新数据

        if (!File.Exists(usJsonPath) || !File.Exists(cnJsonPath))
        {
            throw new BusinessValidationFailedException(StaticData.International("IRaCISCHangfireJob_FileNotFound"));
        }


        //    //监测Json文件变更 实时刷新数据


        FileSystemWatcher_US = new FileSystemWatcher
        {
            Path = Path.GetDirectoryName(usJsonPath)!,
            NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
            Filter = Path.GetFileName(usJsonPath),
            EnableRaisingEvents = true,

        };
        // 添加文件更改事件的处理程序
        FileSystemWatcher_US.Changed += (sender, e) => LoadJsonFile(StaticData.Folder.Resources + "\\" + StaticData.En_US_Json);


        FileSystemWatcher_CN = new FileSystemWatcher
        {
            Path = Path.GetDirectoryName(cnJsonPath)!,
            NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
            Filter = Path.GetFileName(cnJsonPath),
            EnableRaisingEvents = true,

        };
        FileSystemWatcher_CN.Changed += (sender, e) => LoadJsonFile(StaticData.Folder.Resources + "\\" + StaticData.Zh_CN_Json);

    }



    private static void LoadJsonFile(string filePath)
    {
        Console.WriteLine("刷新json内存数据");
        IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile(filePath, false, false);

        IConfigurationRoot enConfiguration = builder.Build();

        foreach (IConfigurationSection section in enConfiguration.GetChildren())
        {
            if (filePath.Contains(StaticData.En_US_Json))
            {
                StaticData.En_US_Dic[section.Key] = section.Value;

            }
            else
            {
                StaticData.Zh_CN_Dic[section.Key] = section.Value;
            }
        }
    }






}
