using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using _Combo;
using System;

namespace _Core
{
    public class I18n
    {
        private static Dictionary<string, string> _dic;
        private static LanguageCode languageCode = LanguageCode.CN;

        public static void Init(Dictionary<string, string> dic = null)
        {
            I18n._dic = dic;
        }

        public static string @T(string key, Dictionary<string, object> pair = null)
        {
            if (null == _dic)
            {
                I18n._dic = LoadLocal();
            }

            if (_dic.ContainsKey(key))
            {
                var i18nValue = _dic[key];
                if (pair != null)
                {
                    foreach (var val in pair)
                    {
                        if (val.Value != null && i18nValue != null)
                        {
                            i18nValue = i18nValue.Replace("#{" + val.Key + "}", val.Value.ToString());
                        }
                    }
                }

                if (!string.IsNullOrEmpty(i18nValue))
                {
                    i18nValue = i18nValue.Replace("\\n", "\n");
                    return i18nValue;
                }
                return "";
            }
            return "@@" + key;
        }

        public static Dictionary<string, string> LoadLocal()
        {
            var lan = GetLanguageCode();
            var textJson = Resources.Load<TextAsset>("Json/i18n");

            var data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(textJson.text);

            if (!data.ContainsKey(lan))
            {
                Log.E($"Failed to load i18n.json, reason: missing language => {lan}");
                return new Dictionary<string, string>();
            }
            Log.I("Finish to load i18n.json");
            return data[lan];
        }

        public static bool IsLanguageSupported(string language)
        {
            var textJson = Resources.Load<TextAsset>("Json/i18n");

            var data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(textJson.text);

            if (data.ContainsKey(language))
            {
                return true;
                
            }
            return false;
        }

        public static void SetLanguageCode(LanguageCode code)
        {
            languageCode = code;
            _dic = LoadLocal();
            Log.I($"local code: {Enum.GetName( typeof (LanguageCode), code)}");
        }

        public static string GetLanguageCode()
        {
            switch (languageCode)
            {
                case LanguageCode.CN:
                    return "zh-cn";
                case LanguageCode.EN:
                default:
                    return "en";
            }
        }
    }
}