using System.Collections.ObjectModel;
using VisionBuilder.UI.Common.Commands;
using VisionBuilder.UI.Common.Commands.Interfaces;
using VisionBuilder.UI.Common.Services;
using VisionBuilder.UI.Common.ViewModel.Classes;
using VisionBuilder.UI.Common.ViewModel.Interfaces.UI;

namespace VisionBuilder.UI.Common.ViewModel;

public class ErrorsVM:IEventHandler<ImageProcessedEvent>, IEventHandler<SessionStartedEvent>
{
    private readonly UIConfiguration _uiConfiguration;
    private readonly IImagePreviewService _imagePreviewService;
    private readonly ILearningTool _learningTool;
    private readonly IPasswordInputService _passwordInputService;

    private const string DATE_FORMAT = "dd.MM.yyyy";
    private const string TIME_FORMAT = "HH:mm:ss";

    public ErrorsVM(UIConfiguration uiConfiguration, IImagePreviewService imagePreviewService, ILearningTool learningTool, IPasswordInputService passwordInputService)
    {
        _uiConfiguration = uiConfiguration;
        _imagePreviewService = imagePreviewService;
        _learningTool = learningTool;
        _passwordInputService = passwordInputService;
    }


    public ObservableCollection<ErrorData> Errors { get; set; } = new ObservableCollection<ErrorData>();

    public async Task ShowImage(ErrorData errorData)
    {
        if (errorData == null) return;

        var vm = new ErrorPreviewVM(this, errorData, errorData.RecipeName, _uiConfiguration, _learningTool, _passwordInputService);
        await _imagePreviewService.ShowImagePreviewAsync(vm);

    }



    public void Handle(ImageProcessedEvent @event)
    {
        if(!@event.HasError)return;

        string additionalInfo = string.Empty;

        var errorShortNames = _uiConfiguration.ErrorShortNames
            .Where(x => @event.ErrorNames.Contains(x.FullName))
            .Select(x => x.ShortName);

        if (errorShortNames.Any())
        {
            additionalInfo += " ," + errorShortNames.FirstOrDefault();
        }

        ErrorData errorData = new ErrorData
        {
            RecipeName = @event.RecipeName,
            ImageOriginal = @event.ImageOriginal,
            ImageAnalysis = @event.ImageAnalysis,
            Title =DateTime.Now.ToString(DATE_FORMAT)+" "+ DateTime.Now.ToString(TIME_FORMAT) + additionalInfo
        };

        if (Errors.Count >= _uiConfiguration.MaxErrorCount)
        {
            Errors.RemoveAt(0);
        }

        Errors.Add(errorData);
    }

    public void Handle(SessionStartedEvent @event)
    {
        Errors.Clear();
    }
}