using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI;
using Microsoft.UI.Xaml;
using NixExampleWinUI.Views;
using NixUniversalSDK;
using Windows.UI;
using Windows.ApplicationModel.Resources;

namespace NixExampleWinUI.ViewModels;

/// <summary>
/// View model for <see cref="ActivateLicenseContentDialog"/>
/// </summary>
public class ActivateLicenseViewModel : ObservableRecipient
{
    private static readonly ResourceLoader Loader = ResourceLoader.GetForViewIndependentUse();

    private string? _options = LicenseKey.Options;
    
    /// <summary>
    /// User entered options string
    /// </summary>
    public string Options
    {
        get => _options ?? string.Empty;
        set
        {
            SetProperty(ref _options, value);
            OnPropertyChanged(nameof(ActivateButtonEnabled));
        }
    }

    private string? _signature = LicenseKey.Signature;
    
    /// <summary>
    /// User entered signature string
    /// </summary>
    public string Signature
    {
        get => _signature ?? string.Empty;
        set
        {
            SetProperty(ref _signature, value);
            OnPropertyChanged(nameof(ActivateButtonEnabled));
        }
    }

    /// <summary>
    /// Enforces that the activate button is only enabled if options and signature have been entered 
    /// </summary>
    public bool ActivateButtonEnabled =>
        !string.IsNullOrEmpty(Options) && !string.IsNullOrEmpty(Signature);

    private LicenseManagerState _lastState = NixUniversalSDK.LicenseManager.State;
    
    /// <summary>
    /// Stored value of the last license activation result
    /// </summary>
    public LicenseManagerState LastState
    {
        get => _lastState;
        set
        {
            SetProperty(ref _lastState, value);
            StatusMessageVisibility = Visibility.Visible;
            OnPropertyChanged(nameof(StatusMessage));
            OnPropertyChanged(nameof(StatusMessageColor));
            OnPropertyChanged(nameof(StatusMessageVisibility));
        }
    }

    /// <summary>
    /// Status message, based on the result of the last license activation
    /// </summary>
    public string StatusMessage => string.Format(Loader.GetString("MessageActivationStatus"), LastState.ToString());

    /// <summary>
    /// Status message color, based on the result of the last license activation
    /// </summary>
    public Color StatusMessageColor => LastState switch 
    {
        LicenseManagerState.Active => Colors.LightGreen,
        _ => Colors.OrangeRed
    };

    /// <summary>
    /// Visibility flag for the status message
    /// </summary>
    public Visibility StatusMessageVisibility = Visibility.Collapsed;
}