using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WCS.BLL.Config
{
    /// <summary>
    /// 本地文件
    /// </summary>
    public static class LocalFile
    {

        public static readonly string AppDir = AppDomain.CurrentDomain.BaseDirectory;
        /// <summary>
        /// 程序运行名称（BaseUi.exe）
        /// </summary>
        public static readonly string AppName = AppDomain.CurrentDomain.FriendlyName;
        /// <summary>
        /// 数据目录
        /// </summary>
        public static readonly string DataDir = Path.Combine(AppDir, "data");
        /// <summary>
        /// 日志目录
        /// </summary>
        public static readonly string LogDir = Path.Combine(AppDir, "logs");
        /// <summary>
        /// 配置文件路径
        /// </summary>
        public static readonly string ConfigPath = Path.Combine(DataDir, "jsconfig.json");
        /// <summary>
        /// 货架模组编码正则表达式
        /// </summary>
        public static readonly string DefaultModuleCodePattern = "^[ABCD][0-9]{1,2}-R[0-9]{1,2}C[0-9]{1,2}$";

        static object lockConfig = new object();

        static JsConfig config;
        /// <summary>
        /// 配置信息
        /// </summary>
        public static JsConfig Config
        {
            get
            {
                if (config != null)
                    return config;
                else
                {
                    try
                    {
                        if (File.Exists(ConfigPath))
                            lock (lockConfig)
                                config = JsonConvert.DeserializeObject<JsConfig>(File.ReadAllText(ConfigPath, Encoding.UTF8));
                        else
                            config = null;
                    }
                    catch (Exception)
                    {
                        config = null;
                    }
                }
                return config ?? new JsConfig();
            }
        }

        /// <summary>
        /// 刷新配置信息。将本地的配置信息重新加载到内存中
        /// </summary>
        public static void UpdateConfig()
        {
            if (File.Exists(ConfigPath))
                lock (lockConfig)
                    config = JsonConvert.DeserializeObject<JsConfig>(File.ReadAllText(ConfigPath, Encoding.UTF8));
            else
                config = null;
        }

        /// <summary>
        /// 保存配置信息。将内存中的配置信息保存到本地
        /// </summary>
        public static void SaveConfig()
        {
            try
            {
                lock (lockConfig)
                    File.WriteAllText(ConfigPath, JsonConvert.SerializeObject(Config, Formatting.Indented), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                UpdateConfig();
                throw ex;
            }
        }
    }
}
