namespace HistoryView.Helper;

public partial class LanguageLoader : ObservableObject
{
    [ObservableProperty]
    private ObservableDictionary<string, Dictionary<object, object>> _Languages = [];

    [ObservableProperty]
    private object? _SelectedLanguage;

    public static string DefaultLanguage { get; } = "中文";

    partial void OnSelectedLanguageChanged(object? value)
    {
        if (value is not KeyValuePair<string, Dictionary<object, object>> items)
            return;

        foreach (var item in items.Value)
        {
            if (!App.Current.Resources.Contains(item.Key))
                continue;

            App.Current.Dispatcher.Invoke(() =>
            {
                App.Current.Resources[item.Key] = item.Key switch
                {
                    "LanguageFlag" => new BitmapImage(new Uri(Path.Combine(FilePaths.LanguageBasePath, item.Value.ToString()!))),
                    _ => item.Value,
                };
            });
        }
    }

    public void LoadLanguages(string path)
    {
        this.Languages = [];
        List<string> sheetNames = MiniExcel.GetSheetNames(path);
        foreach (string sheet in sheetNames)
        {
            Dictionary<object, object> tempLang = [];
            var rows = MiniExcel.Query(path, sheetName: sheet).Cast<IDictionary<string, object>>();

            foreach (var row in rows)
            {
                if (!row.TryGetValue("A", out object? A) || !row.TryGetValue("B", out object? B))
                    continue;

                if (A is null || B is null)
                    continue;

                tempLang[A] = B;
            }

            this.Languages[sheet] = tempLang;
        }

        foreach (var item in this.Languages)
        {
            if (item.Key != DefaultLanguage)
                continue;
            this.SelectedLanguage = item;
        }
    }
}
