using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
using System;

namespace TFramework
{
    public class LanguageManager : BaseManager
    {
        public LanguageData m_languageData;

        public string m_initKind;

        private string _currentKind;

        public string CurrentKind => _currentKind;

        private string lastKind;

        private Dictionary<string, string> kindFieldDic = new Dictionary<string, string>();

        string[] kinds;

        private void Awake()
        {
            if(m_languageData!=null)
            {
                FieldInfo[] fieldInfos = GlobalTool.GetTypesInRunTimeAssemblies(type => type.FullName == m_languageData.m_languageType)[0].GetFields();

                kinds = new string[fieldInfos.Length];
                for (int i = 0; i < fieldInfos.Length; i++)
                {
                    LanguageAttribute attribute = fieldInfos[i].GetCustomAttribute<LanguageAttribute>();
                    kinds[i] = attribute != null ? attribute.LanguageType : fieldInfos[i].Name;
                    if (!kindFieldDic.ContainsKey(kinds[i]))
                    {
                        kindFieldDic.Add(kinds[i], fieldInfos[i].Name);
                    }
                }
            }
            _currentKind = m_initKind;
            lastKind = m_initKind;
        }

        /// <summary>
        /// 获取语言种类
        /// </summary>
        public string[] GetLanguageKindArray() => kinds;

        /// <summary>
        /// 切换语言
        /// </summary>
        /// <param name="kind">语种</param>
        public void ChangeLanguage(string kind)
        {
            lastKind = _currentKind;
            _currentKind = kind;
            Main.GetMagr<UIManager>().ChangedWord();
        }

        internal string GetLanguageText(string text)
        {
            string v = string.Empty;
            foreach (var item in m_languageData.m_languages)
            {
                if(item.GetType().GetField(kindFieldDic[lastKind]).GetValue(item).ToString()==text)
                {
                    v = item.GetType().GetField(kindFieldDic[CurrentKind]).GetValue(item).ToString();
                    break;
                }
            }
            return v;
        }
    }
}