using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace desktopEnglish.utils
{
    class JsonUtil
    {
        public static void WriterJson(string jsonPath, Dictionary<string, string> dicJsons)
        {
            try
            {
                string json = File.ReadAllText(jsonPath);
                dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

                foreach (var item in dicJsons)
                {
                    jsonObj[item.Key] = item.Value;
                }
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(jsonPath, output);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static Dictionary<string, string> ReaderJson(string jsonPath)
        {
            Dictionary<string, string> disJsons = new Dictionary<string, string>();
            try
            {
                StreamReader file = File.OpenText(jsonPath);
                JsonTextReader reader = new JsonTextReader(file);
                JObject jsonObject = (JObject)JToken.ReadFrom(reader);

                foreach (var item in jsonObject)
                {
                    disJsons.Add(item.Key, item.Value.ToString());
                }

                reader.Close();
                file.Close();
                return disJsons;
            }
            catch
            {
                return null;
            }
        }
    }
}
