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

namespace VisionBuilder.UI.Blazor.Components;

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

    private string _sessionStarted = "";
    private string _recipeName = "";
    private string _processingTime = "";
    private int _good;
    private int _bad;
    private int _total;
    private string _errorRate = "";
    private string _statisticsDetails = "";
    private StatisticsVM? _subscribedVm;
    private bool _disposed;

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

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

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

    private async void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
    {
        if (_disposed) return;

        _sessionStarted = ViewModel?.SessionStarted ?? "";
        _recipeName = ViewModel?.RecipeName ?? "";
        _processingTime = ViewModel?.ProcessingTime ?? "";
        _good = ViewModel?.Good ?? 0;
        _bad = ViewModel?.Bad ?? 0;
        _total = ViewModel?.Total ?? 0;
        _errorRate = ViewModel?.ErrorRate ?? "";
        _statisticsDetails = ViewModel?.StatisticsDetails ?? "";

        await InvokeAsync(StateHasChanged);
    }

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