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

namespace OnlineStore.Common
{
    public class SMF
    {
        public static string DeviceType = "OUT";
        static string _server = Setting_Init.Device_Server_Address;
        static string server
        {
            get
            {
                //_server = "http://192.168.1.243/smf-core";
                if (_server.EndsWith("/"))
                {
                    return _server.Remove(_server.Length - 1, 1);
                }
                else
                    return _server;
            }
        }
        public static bool UploadLangJsonData(string json, out SmfResult smfResult)
        {
            var insertindex = json.IndexOf("{");
            json = json.Insert(insertindex + 1, "\"type\": \"" + DeviceType + "\",");
            return UploadJsonData("/api/translation/resource", json, out smfResult);
        }
        public static bool UploadJsonData(string api, string json, out SmfResult smfResult)
        {
            smfResult = new SmfResult();
            if (string.IsNullOrEmpty(server))
                return false;            
            try
            {
                MyWebClient wc = new MyWebClient(10 * 1000);
                wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
                var resp = wc.UploadData(server + api, Encoding.UTF8.GetBytes(json));
                smfResult = JsonHelper.DeserializeJsonToObject<SmfResult>(Encoding.UTF8.GetString(resp));
            }
            catch (Exception e)
            {
                LogUtil.info($"UploadJsonData:{api}" + e.ToString());
            }
            return smfResult.okResult;
        }
        public static List<SmfLangData> DownloadLngData()
        {
            string api = "/api/translation/resource?type=" + DeviceType;
            try
            {
                MyWebClient wc = new MyWebClient(10 * 1000);
                wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
                var resp = wc.DownloadData(server + api);
                var jsondata = Encoding.UTF8.GetString(resp);
                return JsonConvert.DeserializeObject<List<SmfLangData>>(jsondata);
            }
            catch (Exception e)
            {
                LogUtil.info($"DownloadLngData:{api}" + e.ToString());
            }

            return new List<SmfLangData>();
        }
    }

    //{"code":0,"data":"ok","msg":"ok","msgKey":"smfcore.ok","okResult":true}
    public class SmfResult
    {
        public int code;
        public string data;
        public string msg;
        public string msgKey;
        public bool okResult;
    }

    public class SmfLangData
    {
        public string lanCode;
        public Dictionary<string, string> resourceMap;
    }


}