using Atomx.Admin.Client.Services;
using Atomx.Data.CacheServices;
using Atomx.Data.Services;

namespace Atomx.Admin.Services
{
    public class LocalizationService : ILocalizationService
    {
        private readonly ICacheService _cacheService;
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<LocalizationService> _logger;

        public event EventHandler<string>? ResourcesUpdated;

        public LocalizationService(
            ICacheService cacheService,
            IWebHostEnvironment environment,
            ILogger<LocalizationService> logger)
        {
            _cacheService = cacheService;
            _environment = environment;
            _logger = logger;
        }

        /// <summary>
        /// 根据name获取制定文化语言的译文
        /// </summary>
        /// <param name="name"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public async Task<string?> GetStringAsync(string name, string? culture = null)
        {
            culture ??= Thread.CurrentThread.CurrentCulture.Name;

            return await _cacheService.GetLocaleResourcesString(culture, name);
        }

        /// <summary>
        /// 加载资源到内存
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public async Task<bool> LoadResourcesAsync(string culture)
        {
            await _cacheService.GetLocaleResourcesAsync(culture);
            return true;
        }


        private string GetJsonFilePath(string culture)
        {
            return Path.Combine(_environment.WebRootPath, "locales", $"{culture}.json");
        }

        /// <summary>
        /// 计算文件哈希值
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static string CalculateFileHash(string filePath)
        {
            using var stream = File.OpenRead(filePath);
            using var sha256 = System.Security.Cryptography.SHA256.Create();
            var hash = sha256.ComputeHash(stream);
            return Convert.ToBase64String(hash);
        }


    }
}