using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using NixExampleWinUI.Models;
using NixUniversalSDK;
using Windows.ApplicationModel.Resources;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace NixExampleWinUI.Views;

/// <summary>
/// Custom <see cref="ContentDialog"/> used for Nix device field calibration in the Nix Example app
/// </summary>
public sealed partial class CalibrateContentDialog : ContentDialog
{
    private static readonly ResourceLoader Loader = ResourceLoader.GetForViewIndependentUse();
    private readonly DeviceModel DeviceModel;
    private bool IsDeviceBusy => DeviceModel.Device?.State switch
    {
        DeviceState.Idle or DeviceState.Disconnected or null => false,
        _ => true,
    };

    public CalibrateContentDialog()
    {
        this.InitializeComponent();

        // Get DeviceModel singleton (connected IDeviceCompat instance exists here)
        DeviceModel = App.GetService<DeviceModel>();
    }

    private void ContentDialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args)
    {
        // Prevents dialog from closing while the device is busy
        if (IsDeviceBusy) { args.Cancel = true; }
    }

    private async void AcceptButton_Click(object sender, RoutedEventArgs e)
    {
        // Prevent the text box from being edited and this button from being clicked
        TileKeyTextBox.IsEnabled = false;
        AcceptButton.IsEnabled = false;

        // Clear status message
        StatusMessage.Text = string.Empty;

        if (DeviceModel.Device is IDeviceCompat device)
        {
            // Check the tile string
            if (device.IsTileStringValid(TileKeyTextBox.Text) == true)
            {
                // String is valid, start the calibration routine
                CalibrationProgressBar.Visibility = Visibility.Visible;
                var result = await device.RunFieldCalibrationAsync(TileKeyTextBox.Text);                
                var status = result?.Status ?? CommandStatus.ErrorInternal;
                CalibrationProgressBar.Visibility = Visibility.Collapsed;

                // Show status message
                StatusMessage.Text = string.Format(Loader.GetString("MessageCalibrationStatus"), status.GetName());
                var messageColor = status == CommandStatus.Success ? Colors.LightGreen : Colors.OrangeRed;
                StatusMessage.Foreground = new SolidColorBrush(messageColor);
            }
            else
            {
                // Tile string is invalid
                StatusMessage.Text = Loader.GetString("MessageTileStringError");
                StatusMessage.Foreground = new SolidColorBrush(Colors.OrangeRed);
            }
        }
        else
        {
            // Could not get device instance
            StatusMessage.Text = Loader.GetString("MessageDeviceNotAvailable");
            StatusMessage.Foreground = new SolidColorBrush(Colors.OrangeRed);
        }

        // Allow editing
        TileKeyTextBox.IsEnabled = true;
        AcceptButton.IsEnabled = true;
    }
}