using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using VisionBuilder.UI.Common.Commands;
using VisionBuilder.UI.Common.Commands.Interfaces;
using VisionBuilder.UI.Common.ViewModel.Classes;
using VisionBuilder.UI.Common.ViewModel.Interfaces.UI;

namespace VisionBuilder.UI.Common.ViewModel;

public partial class MainWindowVM:ObservableObject
{
    private readonly ISettingsService _settingsService;
    public event Action ProgramStarted = delegate { };
    public event Action ProgramClosed = delegate { };
    public event Action<bool> TestModeChanged = delegate { };

    [ObservableProperty]
    private bool _testMode;

    public MainWindowVM(ISettingsService settingsService)
    {
        _settingsService = settingsService;
    }

    public ObservableCollection<SingleCameraVM> SingleCameraVms { get; set; } =
        new ObservableCollection<SingleCameraVM>();

    public ObservableCollection<ButtonDefinition> DynamicButtons { get; } = new();

    public void AddButton(ButtonDefinition button)
    {
        DynamicButtons.Add(button);
    }

    public void SetButtonVisibility(string key, bool isVisible)
    {
        var button = DynamicButtons.FirstOrDefault(b => b.Key == key);
        if (button != null)
            button.IsVisible = isVisible;
    }

    public void RemoveButton(string key)
    {
        var button = DynamicButtons.FirstOrDefault(b => b.Key == key);
        if (button != null)
            DynamicButtons.Remove(button);
    }


    [RelayCommand]
    public async Task Settings()
    {
        await _settingsService.ShowSettingsDialogAsync();
    }

    [RelayCommand]
    public void ToggleTestMode()
    {
        TestMode = !TestMode;
        TestModeChanged(TestMode);
    }

    public void OnProgramStarted()
    {
        ProgramStarted?.Invoke();
    }

    public void OnProgramClosed()
    {
        foreach (var singleCameraVm in SingleCameraVms)
        {
            if (singleCameraVm.IsRunning)
            {
                singleCameraVm.StopCommand.Execute(null);
                
            }
        }
        ProgramClosed?.Invoke();
    }

}