using CommunityToolkit.Mvvm.ComponentModel;
using System.Text;
using System.Threading;
using VisionBuilder.UI.Common.Commands;
using VisionBuilder.UI.Common.Commands.Interfaces;


namespace VisionBuilder.UI.Common.ViewModel;

public partial class StatisticsVM: ObservableObject,IEventHandler<ImageProcessedEvent>, IEventHandler<SessionStartedEvent>
{

    [ObservableProperty] private string _sessionStarted;
    [ObservableProperty] private string _recipeName;

    [ObservableProperty] private string _processingTime="";

    [ObservableProperty] private int _good;
    [ObservableProperty] private int _bad;
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(ErrorRate))]
    private int _total;

    [ObservableProperty] private string _statisticsDetails="";

    public string ErrorRate => _bad/(float)_total * 100 + "%";

    private readonly Dictionary<string, int> _errorTypes = new();

    public void Handle(ImageProcessedEvent @event)
    {

        RecipeName= @event.RecipeName;
        ProcessingTime = (int)@event.AnalysisTime.TotalMilliseconds + "ms";
        Total++;

        if (!@event.HasError)
        {
            Good++;
            return;
        }
        
        Bad++;
        foreach (var name in @event.ErrorNames)
        {
            _errorTypes[name] = _errorTypes.TryGetValue(name, out var count) ? count + 1 : 1;
        }

        StatisticsDetails = string.Join(Environment.NewLine, _errorTypes.OrderBy(e=>e.Key).Select(e => $"{e.Key}: {e.Value}"));
        
    }

    public void Handle(SessionStartedEvent @event)
    {
        // reset everything
        _good = 0;
        _bad = 0;
        _total = 0;
        _errorTypes.Clear();
        SessionStarted = @event.SessionStarted.ToString("yyyy-MM-dd HH:mm:ss");
    }
}