using Cryville.Common.Font;
using Cryville.Common.Unity.UI;
using Cryville.Culture;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using UnityEngine;

namespace Cryville.EEW.Unity {
	class App {
		static bool _init;
		public static void Init() {
			if (_init) return;
			_init = true;

			foreach (var res in Resources.LoadAll<TextAsset>("cldr/common/validity")) {
				IdValidity.Load(LoadXmlDocument(res));
			}
			var metadata = new SupplementalMetadata(LoadXmlDocument("cldr/common/supplemental/supplementalMetadata"));
			var subtags = new LikelySubtags(LoadXmlDocument("cldr/common/supplemental/likelySubtags"), metadata);
			var matcher = new LanguageMatching(LoadXmlDocument("cldr/common/supplemental/languageInfo"), subtags);
			TMPLocalizedText.FontMatcher = new FallbackListFontMatcher(matcher, PlatformConfig.FontManager) {
				MapScriptToTypefaces = PlatformConfig.ScriptFontMap
			};
			TMPLocalizedText.DefaultShader = Resources.Load<Shader>(PlatformConfig.TextShader);

			SharedSettings.Instance.Init();
		}

		static readonly Encoding _encoding = new UTF8Encoding(false, true);
		static readonly XmlReaderSettings _xmlSettings = new() {
			DtdProcessing = DtdProcessing.Ignore,
		};
		static XDocument LoadXmlDocument(string path) {
			return LoadXmlDocument(Resources.Load<TextAsset>(path));
		}
		static XDocument LoadXmlDocument(TextAsset asset) {
			using var stream = new MemoryStream(_encoding.GetBytes(asset.text));
			using var reader = XmlReader.Create(stream, _xmlSettings);
			return XDocument.Load(reader);
		}
	}
}
