using LitJson;
using System.IO;
using UnityEngine;

namespace WS
{
    ///<summary>加载配置文件</summary>
    public static class ConfigHelper
    {
        ///<summary>加载配置文件</summary>
        public static T LoadConfig<T>(string path)
        {
            TextAsset asset = Resources.Load<TextAsset>(path);
            T t = JsonMapper.ToObject<T>(asset.text);
            return t;
        }

        ///<summary>全路径加载</summary>
        public static T FileLoadConfig<T>(string path) where T : new()
        {
            using (StreamReader sr = new StreamReader(path))
            {
                T config = JsonMapper.ToObject<T>(sr.ReadToEnd());
                if (config == null)
                {
                    config = new T();
                }
                return config;
            }
        }

        /// <summary>保存Config</summary>
        public static void SaveConfig(object config, string path)
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Create))
            {
                byte[] bytes = JsonMapper.ToJson(config).ToByteArray();
                fileStream.Write(bytes, 0, bytes.Length);
            }
        }

        /// <summary>文件是否存在 不存在则创建</summary>
        public static bool ConfigExists(string path)
        {
            if (File.Exists(path))
            {
                return true;
            }
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            fs.Close();
            return true;
        }
    }
}
