using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using NexusShell.Services;

namespace NexusShell.ViewModels;

public sealed class NexusCalculatorViewModel : INotifyPropertyChanged
{
    private readonly NexusCalculatorService _calculator;

    public NexusCalculatorViewModel(NexusCalculatorService calculator)
    {
        _calculator = calculator;
        ButtonCommand = new RelayCommand(p => Press(p as string));
        CloseCommand = new RelayCommand(_ => CloseRequested?.Invoke(this, EventArgs.Empty));
    }

    public event PropertyChangedEventHandler? PropertyChanged;
    public event EventHandler? CloseRequested;

    public string Title => "Nexus Calculator";

    public string ModeLabel => _calculator.ModeLabel;

    public string ExpressionLine => _calculator.ExpressionLine;

    public string Display => _calculator.Display;

    public ICommand ButtonCommand { get; }

    public ICommand CloseCommand { get; }

    public void Press(string? buttonId)
    {
        if (string.IsNullOrWhiteSpace(buttonId))
        {
            return;
        }

        _calculator.PressButton(buttonId);
        NotifyDisplayChanged();
    }

    public void Reset()
    {
        _calculator.Reset();
        NotifyDisplayChanged();
    }

    private void NotifyDisplayChanged()
    {
        OnPropertyChanged(nameof(ExpressionLine));
        OnPropertyChanged(nameof(Display));
    }

    private void OnPropertyChanged([CallerMemberName] string? name = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
