using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using AdvancedCalculator.Models;
using AdvancedCalculator.Services;

namespace AdvancedCalculator.ViewModels;

public partial class MainViewModel : ViewModelBase
{
    private readonly ICalculatorService _calculatorService;

    public MainViewModel()
        : this(new CalculatorService())
    {
    }

    public MainViewModel(ICalculatorService calculatorService)
    {
        _calculatorService = calculatorService;
        History = new ObservableCollection<HistoryItem>();
        Variables = new ObservableCollection<VariableItem>();
    }

    [ObservableProperty]
    private string _inputText = string.Empty;

    [ObservableProperty]
    private bool _isFunctionsPanelOpen;

    [ObservableProperty]
    private int _selectedHistoryIndex = -1;

    public ObservableCollection<HistoryItem> History { get; }
    public ObservableCollection<VariableItem> Variables { get; }

    [RelayCommand]
    private void ToggleFunctions()
    {
        IsFunctionsPanelOpen = !IsFunctionsPanelOpen;
    }

    [RelayCommand(AllowConcurrentExecutions = false)]
    private async Task Submit()
    {
        var text = InputText?.Trim();
        if (string.IsNullOrEmpty(text))
            return;

        var result = await _calculatorService.InterpretAsync(text);

        History.Add(new HistoryItem { Input = text, Output = result.Output });

        Variables.Clear();
        foreach (var v in result.Variables)
        {
            Variables.Add(v);
        }

        InputText = string.Empty;
        SelectedHistoryIndex = History.Count - 1;
    }
}
