using Newtonsoft.Json;

namespace SHH.MjpegPlayer;

/// <summary>
/// Json 配置文件
/// </summary>
public class JsonConfig
{
    #region Load

    /// <summary>
    /// 加载配置
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static T? Load<T>(string path)
    {
        try
        {
            var newPath = $"{Environment.CurrentDirectory}\\{path}";
            path = newPath.Replace("Res\\Plugins\\", "");
            var sr = new StreamReader(path);
            var data = sr.ReadToEnd();
            sr.Close();
            sr = null;

            data = data.Replace(@"""$schema"": ""https://gitee.com/dotnetchina/Furion/raw/v4/schemas/v4/furion-schema.json"",", "");

            var obj = JsonConvert.DeserializeObject<T>(data);
            //Logs.LogInformation<JsonConfig>(EIdFiles.LoadSucceed,
            //    $"配置{EIdFiles.LoadSucceed.GetDescription()}, Path:{path} 类型:{typeof(T).FullName}.");
            return obj;
        }
        catch (Exception ex)
        {
            //Logs.LogWarning<JsonConfig>(EIdFiles.LoadFailed,
            //    $"配置{EIdFiles.LoadSucceed.GetDescription()}, Path:{path} 类型:{typeof(T).FullName}.", ex.Message, ex.StackTrace);
            return default(T);
        }
    }

    #endregion

    #region Save

    /// <summary>
    /// 保存配置
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="path"></param>
    /// <param name="caption"></param>
    /// <returns></returns>
    public static bool Save(object obj, string path, string caption)
    {
        try
        {
            var newPath = Path.GetFullPath(path);
            if (File.Exists(newPath))
                File.Delete(newPath);

            var loc = newPath.LastIndexOf("\\");
            if (loc > 0)
            {
                var newDir = newPath.Substring(0, loc);
                Directory.CreateDirectory(newDir);
            }

            var msg = JsonConvert.SerializeObject(obj, Formatting.Indented);
            msg = msg.Insert(1, "\"$schema\": \"https://gitee.com/dotnetchina/Furion/raw/v4/schemas/v4/furion-schema.json\",\r\n");

            var sw = new StreamWriter(newPath);
            sw.Write(msg);
            sw.Flush();
            sw.Close();
            sw = null;

            //Logs.LogInformation<JsonConfig>(EIdFiles.SaveSucceed,
            //    $"配置{EIdFiles.SaveSucceed.GetDescription()}, Path:{path}\r\n\t\t\tCaption:{caption} 类型:{obj.GetType().FullName}.");

            return true;
        }
        catch (Exception ex)
        {
            //Logs.LogInformation<JsonConfig>(EIdFiles.SaveFailed,
            //    $"配置{EIdFiles.SaveFailed.GetDescription()}, Path:{path}\r\n\t\t\tCaption:{caption} 类型:{obj.GetType().FullName}.", ex.Message, ex.StackTrace);

            return false;
        }
    }

    #endregion
}