using System.Reflection;
using Luski.Classes;
using Luski.GUI.MainScreen.UI.LuskiSettings.Core;

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

public class General : PageFlow
{
    public General()
    {
        PageName = "General";
        foreach (PropertyInfo prop in typeof(Settings).GetProperties())
        {
            object PropVal = prop.GetValue(Globals.Settings)!;
            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.Settings, e);
                            }
                            Globals.Settings.SaveSettings(Path.Combine(Globals.LuskiPath, "Settings.json"), SettingsContext.Default.Settings);
                        });
                    }
                    catch
                    {
                        //ignore
                    }
                }
            }
            if (PropType.FullName == typeof(bool).FullName)
            {
                try
                {
                    Globals.AddBool(this, prop, (bool)PropVal, b =>
                    {
                        prop.SetValue(Globals.Settings, b);
                        Globals.Settings.SaveSettings(Path.Combine(Globals.LuskiPath, "Settings.json"), SettingsContext.Default.Settings);
                    });
                }
                catch
                {
                    // ignored
                }
            }
        }
    }
}