using System.Globalization;
using System.Threading.Channels;
using ErsatzTV.Application.Libraries;
using ErsatzTV.Core;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.FFmpeg.Runtime;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace ErsatzTV.Application.Emby;

public class CallEmbyShowScannerHandler : CallLibraryScannerHandler<SynchronizeEmbyShowById>,
    IRequestHandler<SynchronizeEmbyShowById, Either<BaseError, string>>
{
    public CallEmbyShowScannerHandler(
        IDbContextFactory<TvContext> dbContextFactory,
        IConfigElementRepository configElementRepository,
        ChannelWriter<ISearchIndexBackgroundServiceRequest> channel,
        IMediator mediator,
        IRuntimeInfo runtimeInfo)
        : base(dbContextFactory, configElementRepository, channel, mediator, runtimeInfo)
    {
    }

    Task<Either<BaseError, string>> IRequestHandler<SynchronizeEmbyShowById, Either<BaseError, string>>.Handle(
        SynchronizeEmbyShowById request,
        CancellationToken cancellationToken) => Handle(request, cancellationToken);

    private async Task<Either<BaseError, string>> Handle(
        SynchronizeEmbyShowById request,
        CancellationToken cancellationToken)
    {
        Validation<BaseError, string> validation = await Validate(request, cancellationToken);
        return await validation.Match(
            scanner => PerformScan(scanner, request, cancellationToken),
            error =>
            {
                foreach (ScanIsNotRequired scanIsNotRequired in error.OfType<ScanIsNotRequired>())
                {
                    return Task.FromResult<Either<BaseError, string>>(scanIsNotRequired);
                }

                return Task.FromResult<Either<BaseError, string>>(error.Join());
            });
    }

    private async Task<Either<BaseError, string>> PerformScan(
        string scanner,
        SynchronizeEmbyShowById request,
        CancellationToken cancellationToken)
    {
        var arguments = new List<string>
        {
            "scan-emby-show",
            request.EmbyLibraryId.ToString(CultureInfo.InvariantCulture),
            request.ShowId.ToString(CultureInfo.InvariantCulture)
        };

        if (request.DeepScan)
        {
            arguments.Add("--deep");
        }

        return await base.PerformScan(scanner, arguments, cancellationToken);
    }

    protected override Task<DateTimeOffset> GetLastScan(
        TvContext dbContext,
        SynchronizeEmbyShowById request,
        CancellationToken cancellationToken) =>
        Task.FromResult(DateTimeOffset.MinValue);

    protected override bool ScanIsRequired(
        DateTimeOffset lastScan,
        int libraryRefreshInterval,
        SynchronizeEmbyShowById request) =>
        true;
}
