//using Nancy;
//using Nancy.Hosting.Self;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 电子展板.Models;
using 电子展板.Utility.Core;
using 电子展板.Utility.Extension;

namespace 电子展板.Base
{
    public class GlobalVariable
    {
        //public static NancyHost WebServer;

        private static MyConfig _config;
        /// <summary>
        /// 配置数据
        /// </summary>
        public static MyConfig Config
        {
            get
            {
                if (_config == null)
                {
                    try
                    {
                        _config = File.ReadAllText(MyEnvironment.Root("/Config.json"), Encoding.UTF8).ToObject<MyConfig>();
                        //删除缓存没用到的图片
                        List<string> list = new List<string>
                        {
                            _config.CPCMember1Path,
                            _config.CPCMember2Path,
                            _config.CPCMember3Path,
                            _config.CPCMember4Path
                        };
                        list = list.Where(it => !it.IsNullOrEmpty()).Select(it => it.Replace("/upload/", "")).ToList();
                        if (_config.FileUploadList == null)
                            _config.FileUploadList = new List<UploadFiles>();
                        _config.FileUploadList = _config.FileUploadList.Where(it => list.Contains(it.Name)).ToList();
                        File.WriteAllText(MyEnvironment.Root("/Config.json"), _config.ToJson(), Encoding.UTF8);
                    }
                    catch (Exception ex)
                    {
                        string packUri = $"pack://application:,,,/Assets/InitConfig.json";
                        string json = "";
                        using (Stream stream = System.Windows.Application.GetResourceStream(new Uri(packUri, UriKind.RelativeOrAbsolute)).Stream)
                        {
                            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                            {
                                json = new StreamReader(stream, Encoding.UTF8).ReadToEnd();
                            }
                        }
                        _config = json.ToObject<MyConfig>();
                    }
                }
                return _config;
            }
            set
            {
                _config = value;
            }
        }

        public static void SaveConfig()
        {
            File.WriteAllText(MyEnvironment.Root("/Config.json"), Config.ToJson(), Encoding.UTF8);
        }
    }
}
