using Monitoring.Features.Reports.TranslationDictionaries;

namespace Monitoring.Features.Reports;

internal static class Translations
{
	static Translations()
	{
		var dictionaryTypes = typeof(Translations)
			.Assembly.GetTypes()
			.Where(x => typeof(ITranslationDictionary).IsAssignableFrom(x))
			.Where(x => !x.IsAbstract && !x.IsInterface);

		var dictionaries = new List<ITranslationDictionary>();
		foreach (var dictionaryType in dictionaryTypes)
		{
			var dictionary = Activator.CreateInstance(dictionaryType) as ITranslationDictionary
				?? throw new InvalidOperationException($"Can't create instance of {dictionaryType}");
			dictionaries.Add(dictionary);
		}

		Values = dictionaries.ToDictionary(x => (x.LanguageKey, x.Category), x => x.Values);
	}

	private static readonly Dictionary<(string, TranslationDictionaryCategory), IReadOnlyDictionary<string, string>> Values;

	public static string Translate(string language, string key, TranslationDictionaryCategory? category = null)
	{
		var normalizedLanguage = language.Split('-')[0];
		
	
		var supportedLanguages = new[] { "en", "ru", "kk" };
		
		if (!supportedLanguages.Contains(normalizedLanguage))
		{
			normalizedLanguage = "en";
		}
		
		var categoryKey = category ?? TranslationDictionaryCategories.Common;
		
		if (!Values.TryGetValue((normalizedLanguage, categoryKey), out var dictionary))
		{
			if (!Values.TryGetValue(("en", categoryKey), out dictionary))
			{
			
				return key;
			}
		}
		
		if (!dictionary.TryGetValue(key, out var translation))
		{
			return key;
		}
		
		return translation;
	}
}