using CommunityToolkit.Maui.Alerts; // Toast
using CommunityToolkit.Maui.Core; // IToast, ToastDuration

namespace Northwind.Maui.Blazor.Client.Views;

public partial class OrdersPage : ContentPage
{
	public OrdersPage()
	{
		InitializeComponent();

    UpdateBatteryInfo(Battery.Default);
  }

  private void NewWindowButton_Clicked(object sender, EventArgs e)
  {
    Window window = new() { Page = new AppShell() };
    Application.Current.OpenWindow(window);
  }

  private void Battery_BatteryInfoChanged(object sender,
    BatteryInfoChangedEventArgs e)
  {
    UpdateBatteryInfo(Battery.Default);
  }

  private void UpdateBatteryInfo(IBattery battery)
  {
    BatteryStateLabel.Text = battery.State switch
    {
      BatteryState.Charging => "Ładowanie baterii",
      BatteryState.Discharging => "Ładowarka niepodłączona, praca na baterii",
      BatteryState.Full => "Bateria pełna",
      BatteryState.NotCharging => "Bateria nie ładuje się",
      BatteryState.NotPresent => "Brak baterii",
      BatteryState.Unknown => "Stan baterii nieokreślony",
      _ => "Stan baterii nieokreślony"

    };

    BatteryLevelLabel.Text =
      $"Stan naładowania: {(int)(battery.ChargeLevel * 100)}%";
  }

  private void BatterySwitch_Toggled(object sender, ToggledEventArgs e) =>
    WatchBattery(Battery.Default);

  private bool _isBatteryWatched;

  private void WatchBattery(IBattery battery)
  {
    if (!_isBatteryWatched)
    {
      battery.BatteryInfoChanged += Battery_BatteryInfoChanged;
    }
    else
    {
      battery.BatteryInfoChanged -= Battery_BatteryInfoChanged;
    }

    _isBatteryWatched = !_isBatteryWatched;
  }

  private async void Menu_Clicked(object sender, EventArgs e)
  {
    MenuFlyoutItem menu = sender as MenuFlyoutItem;

    if (menu != null)
    {
      await Shell.Current.GoToAsync($"//{menu.CommandParameter}");
    }
  }

  private async void ToastMenu_Clicked(object sender, EventArgs e)
  {
    MenuFlyoutItem menu = sender as MenuFlyoutItem;

    if (menu != null)
    {
      IToast toast = Toast.Make(message: "Wyskakujące powiadomienie",
        duration: ToastDuration.Short, textSize: 18);

      await toast.Show();
    }
  }
}