using System.Reflection;
using GraphicsManager.Enums;
using Luski.Classes;
using Luski.GUI.MainScreen.UI.LuskiControls;
using Luski.GUI.MainScreen.UI.LuskiControls.SettingsMenuBase.Core;

namespace Luski.GUI.MainScreen.UI.LuskiSettings.Pages.AdvancedSettings;

public class Updater : PageFlow
{
    public Updater()
    {
        PageName = "Updater Config";
        TextBox t;
        foreach (PropertyInfo prop in typeof(UpdaterSettings).GetProperties())
        {
            object PropVal = prop.GetValue(Globals.UpdaterSettings)!;
            Type PropType = prop.PropertyType;
            
            if (PropType.IsEnum)
            {
                IEnumerable<Enum> values = Enum.GetValues(PropType).Cast<Enum>();
                foreach (var val in values)
                {
                    try
                    {
                        Globals.AddBool(this, PropType, val, ((Enum)PropVal).HasFlag(val), bb =>
                        {
                            long va = Convert.ToInt64(val);
                            long v = Convert.ToInt64(PropVal);
                            if (bb)
                            {
                                object e = Enum.Parse(PropType, (v + va).ToString());
                                PropVal = e;
                                prop.SetValue(Globals.Settings, e);
                            }
                            else
                            {
                                var e = Enum.Parse(PropType, (v - va).ToString());
                                PropVal = e;
                                prop.SetValue(Globals.UpdaterSettings, e);
                            }
                            Globals.UpdaterSettings.SaveSettings(Path.Combine(Globals.LuskiPath, "UpdaterSettings.json"), UpdaterSettingsContext.Default.UpdaterSettings);
                        });
                    }
                    catch
                    {
                        //ignore
                    }
                }
            }
            if (PropType.FullName == typeof(bool).FullName)
            {
                try
                {
                    Globals.AddBool(this, prop, (bool)PropVal, b =>
                    {
                        prop.SetValue(Globals.UpdaterSettings, b);
                        Globals.UpdaterSettings.SaveSettings(Path.Combine(Globals.LuskiPath, "UpdaterSettings.json"), UpdaterSettingsContext.Default.UpdaterSettings);
                    });
                }
                catch
                {
                    // ignored
                }
            }
        }
        
        WindowLoaded += _ =>
        {
            Globals.ms.ForceUpdate();
            return Task.CompletedTask;
        };
    }
}