using Newtonsoft.Json;
using SimpleCore.Library;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StandardScene.Chained;

namespace StandardScene.Utils
{
    public static class JsonParser
    {
        public static object fileSync = new object();

        public static void WriteJsonFile(TransportDelivery obj)
        {
            try
            {
                lock (fileSync)
                    File.WriteAllText($"log/tasklist/{obj.TaskId}.json",
                    JsonConvert.SerializeObject(obj, Formatting.Indented));
            }
            catch (Exception e)
            {
                Diagnosis.Log("write tasklist error" + ExceptionFormatter.FormatEx(e), "error", true);
            }
        }

        public static string ReadJsonFile(string path)
        {
            lock (fileSync)
            {
                return File.ReadAllText(path);
            }
        }

        // Json->Object
        //DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ChainedDeliveryMission.Delivery));
        public static TransportDelivery Deserialize(string json)
        {
            TransportDelivery obj = new TransportDelivery();

            using MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            JsonConvert.PopulateObject(json, obj);
            return obj;
        }
    }
}
