﻿namespace NetCreditHub.Localization.Dictionaries.Xml
{
    using System.IO;
    using Sources.Xml;

    /// <summary>
    /// 从一个目录中的 XML 文件构建本地化词典.
    /// </summary>
    public class XmlFileLocalizationDictionaryProvider : LocalizationDictionaryProviderBase
    {
        private readonly string _directoryPath;

        /// <summary>
        /// 创建一个新的 <see cref="XmlFileLocalizationDictionaryProvider"/> 对象.
        /// </summary>
        /// <param name="directoryPath">包含相关 XML 文件的目录地址</param>
        public XmlFileLocalizationDictionaryProvider(string directoryPath)
        {
            if (!Path.IsPathRooted(directoryPath))
            {
#pragma warning disable 618
                directoryPath = Path.Combine(XmlLocalizationSource.RootDirectoryOfApplication, directoryPath);
#pragma warning restore 618
            }

            _directoryPath = directoryPath;
        }

        public override void Initialize(string sourceName)
        {
            var fileNames = Directory.GetFiles(_directoryPath, "*.xml", SearchOption.TopDirectoryOnly);

            foreach (var fileName in fileNames)
            {
                var dictionary = CreateXmlLocalizationDictionary(fileName);
                if (Dictionaries.ContainsKey(dictionary.CultureInfo.Name))
                {
                    throw new HubInitializationException($"{sourceName} 源包含多个词典的语言文化: {dictionary.CultureInfo.Name}");
                }

                Dictionaries[dictionary.CultureInfo.Name] = dictionary;

                if (fileName.EndsWith(sourceName + ".xml"))
                {
                    if (DefaultDictionary != null)
                    {
                        throw new HubInitializationException($"本地化源只能有一个默认的本地化字典: {sourceName}");
                    }

                    DefaultDictionary = dictionary;
                }
            }
        }

        protected virtual XmlLocalizationDictionary CreateXmlLocalizationDictionary(string fileName)
        {
            return XmlLocalizationDictionary.BuildFomFile(fileName);
        }
    }
}