using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows;


namespace Misc
{
    public class Culture : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public string Language { get; set; } = "zh";
        
        public string filePath = "culture.json";
        protected string dirPath;
        public List<string> langs { get; } = new List<string>();

        static Dictionary<string, string> langInfos;
        static Culture()
        {

            langInfos = new Dictionary<string, string>
            {
                { "zh", "(zh)中文" },
                { "en", "(en)English" },
                { "ru", "(ru)русский язык" },
                { "fr", "(fr)français" },
                { "de", "(de)dé yǔ" },
                { "ja", "(ja)日本語" },
                { "ko", "(ko)한국어" }
            };
        }
        public static string GetLangInfo(string lang)
        {
            if (langInfos.ContainsKey(lang))
            {
                return langInfos[lang];
            }
            else
            {
                return lang;
            }
        }

        public static LanguageInfo GetLanguageInfo(string lang)
        {
            return new LanguageInfo() { Info = Culture.GetLangInfo(lang), Language = lang };
        }

        public bool Save()
        {
            string fileFullPath = Path.Combine(dirPath, filePath);

            return CultureJsonDb.Save(fileFullPath, this);
        }

        public bool Load()
        {
            //记录加载时的路径。 就算用  System.Environment.CurrentDirectory = rootDir; 改变后， 也能保存回加载时的位置 
            dirPath = System.IO.Directory.GetCurrentDirectory();

            string fileFullPath = Path.Combine(dirPath, filePath);

            return CultureJsonDb.Load(fileFullPath, this);
        }
        void GetOtherLang()
        {
            langs.Clear();
            langs.Add("zh");
            langs.Add("en");

            //添加其它语言包
            string langPath = Path.Combine(dirPath, "lang");
            if (!Directory.Exists(langPath))
                return;

            DirectoryInfo directory = new DirectoryInfo(langPath);
            var dirs = directory.GetDirectories();
            foreach (var dir in dirs)
            {
                string xamlFilePath = Path.Combine(dir.FullName, "StringResource.xaml");
                if (File.Exists(xamlFilePath))
                {
                    langs.Add(dir.Name);
                }
            }

        }
        public void LoadCulture(Type appType)
        {
            Assembly asm = Assembly.GetAssembly(appType);
            string assemblyName = asm.GetName().Name;

            GetOtherLang();

            string language = Language;
            if (language == "zh")
                return;

            //程序集的，只支持 zh,en.  其它都是 lang 文件夹 内的
            ResourceDictionary resourceDictionary = null;
            if (language == "en")
            {
                string uriString = $@"pack://application:,,,/{assemblyName};component/Themes/StringResources/{language}/StringResource.xaml";
                try
                {

                    resourceDictionary = new ResourceDictionary()
                    {
                        Source = new Uri(uriString)
                    };
                }
                catch
                {
                    return;
                }
            }
            else
            {
                string uriString = Path.Combine(dirPath, "lang", language, "StringResource.xaml");
                try
                {
                    using (FileStream fs = new FileStream(uriString, FileMode.Open, FileAccess.Read))
                    {
                        resourceDictionary = (ResourceDictionary)System.Windows.Markup.XamlReader.Load(fs);
                    }
                }
                catch
                {
                    return;
                }
            }
            if (resourceDictionary != null)
            {
                Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
            }
        }
    }

    public class CultureJsonDb
    {
        public static bool Save(string filePath, Culture src)
        {


            CultureJsonDb jsonDb = new CultureJsonDb()
            {
                Language = src.Language
            };
            try
            {
                //string dirPath = Path.GetDirectoryName(filePath);

                //if (!Directory.Exists(dirPath))
                //    Directory.CreateDirectory(dirPath);

                var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonDb);
                File.WriteAllText(filePath, json);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool Load(string filePath, Culture src)
        {
            if (!File.Exists(filePath))
                return false;
            try
            {
                string json = File.ReadAllText(filePath);
                var jsonDb = Newtonsoft.Json.JsonConvert.DeserializeObject<CultureJsonDb>(json);
                src.Language = jsonDb.Language;
                return true;
            }
            catch
            {

                return false;
            }
        }
        public string Language { get; set; } = "zh";
    }

    public class LanguageInfo : INotifyPropertyChanged
    {
        public string Language { get; set; }
        public string Info { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
