using Newtonsoft.Json;
using System;
using System.IO;
using System.Collections.Concurrent;

namespace HBLConsole.Service
{
    /// <summary>
    /// Json参数服务类
    /// </summary>
    public class Json<T> where T : class, new()
    {
        private volatile static Json<T> _Instance;
        public static Json<T> GetInstance => _Instance ?? (_Instance = new Json<T>());
        private Json() { }

        static string path
        {
            get
            {
                Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AccessFile"));
                return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\{typeof(T).Name}.json";
            }
        }

        public T Base { get; set; } = new T();

        /// <summary>
        /// 保存数据
        /// </summary>
        public void Save()
        {
            string outjson = JsonConvert.SerializeObject(Base);
            File.WriteAllText(path, outjson);
        }

        /// <summary>
        /// 获取保存的数据
        /// </summary>
        public void Read()
        {
            if (File.Exists(path))
            {
                string JsonString = File.ReadAllText(path);
                var result = JsonConvert.DeserializeObject<T>(JsonString);
                if (result != null) { Base = result; }
            }
        }


    }
}
