using FLY.OBJComponents.IService;
using FObjBase;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.OBJComponents.Server
{
    //1min 保存一次数据

    public class JsonDist : IJsonDistService
    {

        public event JsonDistValueChangedEventHandler ValueChanged;

        List<DistCell> cells = new List<DistCell>();

        public JsonDist()
        {
            Load();
        }
        

        public void GetValue(string key, AsyncCBHandler asyncCB, object asyncContext)
        {
            var distCell = cells.Find(c => c.Key == key);
            asyncCB(asyncContext, distCell);
        }

        public void SetValue(string key, JObject value)
        {
            var distCell = cells.Find(c => c.Key == key);
            if (distCell == null)
            {
                distCell = new DistCell()
                {
                    Key = key,
                    Time = DateTime.Now,
                    Value = value
                };
                cells.Add(distCell);
            }
            else {
                distCell.Time = DateTime.Now;
                distCell.Value = value;
            }
            ValueChanged?.Invoke(this, new JsonDistValueValueChangedEventArgs() { key = key });
            Save();
        }

        string file_path = "dist.json";
        void Load() 
        {
            if (!File.Exists(file_path))
                return;

            string json = File.ReadAllText(file_path);
            try
            {
                var cells = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DistCell>>(json);
                this.cells = cells;
            }
            catch 
            {
                //异常
            }
            if (cells == null)
                cells = new List<DistCell>();
        }
        void Save() 
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(cells, Formatting.Indented);
            File.WriteAllText(file_path, json);
        }
    }

}
