using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Microsoft.AspNetCore.Components;
using VisionBuilder.UI.Common.ViewModel;
using VisionBuilder.UI.Common.ViewModel.Classes;

namespace VisionBuilder.UI.Blazor.Components;

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

    private List<ErrorData> _errors = new();
    private ErrorsVM? _subscribedVm;
    private bool _disposed;

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

    private void Subscribe()
    {
        _subscribedVm = ViewModel;
        if (ViewModel != null)
        {
            ViewModel.Errors.CollectionChanged += OnCollectionChanged;
            _errors = new List<ErrorData>(ViewModel.Errors);
        }
    }

    private void Unsubscribe()
    {
        if (_subscribedVm != null)
            _subscribedVm.Errors.CollectionChanged -= OnCollectionChanged;
        _subscribedVm = null;
    }

    private async void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        if (_disposed) return;
        if (ViewModel != null)
            _errors = new List<ErrorData>(ViewModel.Errors);
        await InvokeAsync(StateHasChanged);
    }

    private async Task OnErrorClicked(ErrorData errorData)
    {
        if (ViewModel != null)
            await ViewModel.ShowImage(errorData);
    }

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