using common.libs.extends;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace common.libs.database
{
    /// 
    /// 配置文件缓存
    /// 
    /// 
    public interface IConfigDataProvider where T : class, new()
    {
        /// 
        /// 加载
        /// 
        /// 
        Task Load();
        /// 
        /// 加载
        /// 
        /// 
        Task LoadString();
        /// 
        /// 保存
        /// 
        /// 
        /// 
        Task Save(T model);
        /// 
        /// 保存
        /// 
        /// 
        /// 
        Task Save(string jsonStr);
    }
    /// 
    /// 配置文件的文件缓存
    /// 
    /// 
    public sealed class ConfigDataFileProvider : IConfigDataProvider where T : class, new()
    {
        public async Task Load()
        {
            string fileName = GetTableName(typeof(T));
            try
            {
                if (File.Exists(fileName))
                {
                    string str = (await File.ReadAllTextAsync(fileName).ConfigureAwait(false));
                    //Logger.Instance.Error($"read:{fileName}");
                   // Logger.Instance.Error(str);
                    return str.DeJson();
                }
                else
                {
                    Logger.Instance.Warning($"{fileName} 配置文件缺失~");
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Error($"{fileName} 配置文件解析有误~ :{ex}");
            }
            return null;
        }
        public async Task LoadString()
        {
            string fileName = GetTableName(typeof(T));
            if (File.Exists(fileName))
            {
                return (await File.ReadAllTextAsync(fileName).ConfigureAwait(false));
            }
            return string.Empty;
        }
        public async Task Save(T model)
        {
            try
            {
                string fileName = GetTableName(typeof(T));
                //Logger.Instance.Error($"save:{fileName}");
                //Logger.Instance.Error(model.ToJsonIndented());
                await File.WriteAllTextAsync(fileName, model.ToJsonFormat(), Encoding.UTF8).ConfigureAwait(false);
            }
            catch (Exception)
            {
            }
        }
        public async Task Save(string jsonStr)
        {
            try
            {
                string fileName = GetTableName(typeof(T));
                await File.WriteAllTextAsync(fileName, jsonStr, Encoding.UTF8).ConfigureAwait(false);
            }
            catch (Exception)
            {
            }
        }
        private string GetTableName(Type type)
        {
            var attrs = type.GetCustomAttributes(typeof(TableAttribute), false);
            if (attrs.Length > 0)
            {
                return $"{(attrs[0] as TableAttribute).Name}.json";
            }
            return $"{type.Name}.json";
        }
    }
}