using AsReaderSDK4MAUIDemo.Platforms.iOS;

namespace AsReaderSDK4MAUIDemo;

public partial class SettingsPage : ContentPage
{
    private AsReaderDockManager asReaderDockManager;
    private AsReaderDockManagerDelegate asReaderDockManagerDelegate;

    public SettingsPage()
    {
        InitializeComponent();
        Title = "Settings";
        asReaderDockManager = AsReaderDockManager.sharedInstance();
        asReaderDockManagerDelegate = AsReaderDockManagerDelegate.sharedInstance();
        string beep = Preferences.Get("beep", "true");
        if (beep == "true")
        {
            BeepSwitch.IsToggled = true;
        }
        else
        {
            BeepSwitch.IsToggled = false;
        }
        string vibration = Preferences.Get("vibration", "true");
        if (vibration == "true")
        {
            VibrationSwitch.IsToggled = true;
        }
        else
        {
            VibrationSwitch.IsToggled = false;
        }
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        asReaderDockManagerDelegate.Plugged = (plug) =>
        {
            Plugged(plug);
        };
    }
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        asReaderDockManagerDelegate.Plugged = null;
    }
    void OnToggledBeep(object sender, ToggledEventArgs e)
    {
        string beep = e.Value ? "true" : "false";
        Preferences.Set("beep", beep);
        setBeepAndVibration();
    }
    void OnToggledVibration(object sender, ToggledEventArgs e)
    {
        string vibration = e.Value ? "true" : "false";
        Preferences.Set("vibration", vibration);
        setBeepAndVibration();
    }
    private void setBeepAndVibration()
    {
        string beep = Preferences.Get("beep", "true");
        bool beepStatus;
        if (beep == "true")
        {
            beepStatus = true;
        }
        else
        {
            beepStatus = false;
        }
        string vibration = Preferences.Get("vibration", "true");
        bool vibrationStatus;
        if (vibration == "true")
        {
            vibrationStatus = true;
        }
        else
        {
            vibrationStatus = false;
        }
        asReaderDockManager.setBeepAndVibration(beepStatus, vibrationStatus);
    }
    private void Plugged(bool plug)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            if (!plug)
            {
                Navigation.PopToRootAsync();
            }
        });
    }
}
