using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;

namespace ConeCalorimeter.ViewModels;

public sealed class CValueCalibrationActionViewModel : ObservableObject
{
    private bool _isActive;
    private bool _isStatusKnown;
    private bool _isBusy;
    private string _busyDisplayText = string.Empty;

    public CValueCalibrationActionViewModel(
        string label,
        ICommand command,
        string inactiveDisplayText,
        string activeDisplayText,
        bool showStateText = true)
    {
        Label = label;
        Command = command;
        InactiveDisplayText = inactiveDisplayText;
        ActiveDisplayText = activeDisplayText;
        ShowStateText = showStateText;
    }

    public string Label { get; }

    public string InactiveDisplayText { get; }

    public string ActiveDisplayText { get; }

    public bool ShowStateText { get; }

    public ICommand Command { get; }

    public bool IsActive
    {
        get => _isActive;
        private set
        {
            if (SetProperty(ref _isActive, value))
            {
                OnPropertyChanged(nameof(DisplayText));
                OnPropertyChanged(nameof(StatusText));
            }
        }
    }

    public bool IsStatusKnown
    {
        get => _isStatusKnown;
        private set
        {
            if (SetProperty(ref _isStatusKnown, value))
            {
                OnPropertyChanged(nameof(DisplayText));
                OnPropertyChanged(nameof(StatusText));
            }
        }
    }

    public bool IsBusy
    {
        get => _isBusy;
        private set
        {
            if (SetProperty(ref _isBusy, value))
            {
                OnPropertyChanged(nameof(DisplayText));
                OnPropertyChanged(nameof(StatusText));
                OnPropertyChanged(nameof(IsEnabled));
            }
        }
    }

    public bool IsEnabled => !IsBusy;

    public string DisplayText => IsBusy
        ? _busyDisplayText
        : !ShowStateText
        ? Label
        : IsStatusKnown
        ? IsActive ? ActiveDisplayText : InactiveDisplayText
        : $"{Label}：未知";

    public string StatusText => IsBusy
        ? "进行中"
        : IsStatusKnown
        ? IsActive ? "开启" : "关闭"
        : "未知";

    public void UpdateStatus(bool isActive, bool isStatusKnown = true)
    {
        IsStatusKnown = isStatusKnown;
        IsActive = isActive;
    }

    public void BeginWaiting(string busyDisplayText)
    {
        _busyDisplayText = busyDisplayText;
        IsStatusKnown = true;
        IsActive = true;
        IsBusy = true;
        OnPropertyChanged(nameof(DisplayText));
        OnPropertyChanged(nameof(StatusText));
    }

    public void FinishWaiting()
    {
        IsStatusKnown = true;
        IsActive = false;
        IsBusy = false;
    }
}
