using System.ComponentModel;
using Microsoft.AspNetCore.Components;
using VisionBuilder.UI.Common;

namespace VisionBuilder.UI.Blazor.Components;

public partial class SingleCameraControl : ComponentBase, IDisposable
{
    [Parameter] public SingleCameraVM? ViewModel { get; set; }

    private string _cameraLabel = "";
    private string _currentRecipeName = "Select recipe";
    private bool _canSelectRecipe;
    private bool _canStart;
    private bool _canStop;
    private bool _canPause;
    private bool _canResume;
    private bool _canHotReload;
    private bool _showPauseButton;
    private SingleCameraVM? _subscribedVm;
    private bool _disposed;

    protected override void OnParametersSet()
    {
        if (_subscribedVm != ViewModel)
        {
            Unsubscribe();
            Subscribe();
        }
    }

    private void Subscribe()
    {
        _subscribedVm = ViewModel;
        if (ViewModel != null)
        {
            ViewModel.PropertyChanged += OnPropertyChanged;
            UpdateState();
        }
    }

    private void Unsubscribe()
    {
        if (_subscribedVm != null)
            _subscribedVm.PropertyChanged -= OnPropertyChanged;
        _subscribedVm = null;
    }

    private void UpdateState()
    {
        if (ViewModel == null) return;
        _cameraLabel = ViewModel.CameraLabelAndStatus;
        _currentRecipeName = ViewModel.CurrentRecipeName;
        _canSelectRecipe = ViewModel.IsNotRunning;
        _canStart = ViewModel.CanStart;
        _canStop = ViewModel.CanStop;
        _canPause = ViewModel.CanPause;
        _canResume = ViewModel.CanResume;
        _canHotReload = ViewModel.CanHotReload;
        _showPauseButton = ViewModel.CanPause || ViewModel.CanResume;
    }

    private async void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
    {
        if (_disposed) return;
        UpdateState();
        await InvokeAsync(StateHasChanged);
    }

    private async Task OnSelectRecipe()
    {
        if (ViewModel?.SelectRecipeCommand.CanExecute(null) == true)
            await ViewModel.SelectRecipe();
    }

    private async Task OnStart()
    {
        if (ViewModel?.StartCommand.CanExecute(null) == true)
            await ViewModel.Start();
    }

    private async Task OnStop()
    {
        if (ViewModel?.StopCommand.CanExecute(null) == true)
            await ViewModel.Stop();
    }

    private void OnPause()
    {
        if (ViewModel?.PauseCommand.CanExecute(null) == true)
            ViewModel.PauseCommand.Execute(null);
    }

    private void OnResume()
    {
        if (ViewModel?.ResumeCommand.CanExecute(null) == true)
            ViewModel.ResumeCommand.Execute(null);
    }

    private void OnHotReload()
    {
        if (ViewModel?.HotReloadCommand.CanExecute(null) == true)
            ViewModel.HotReloadCommand.Execute(null);
    }

    public void Dispose()
    {
        _disposed = true;
        Unsubscribe();
    }
}
