// <copyright file="FfProbeKeyframeExtractor.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace Jellyfin.MediaEncoding.Hls.Extractors;

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Emby.Naming.Common;
using Jellyfin.Extensions;
using Jellyfin.MediaEncoding.Keyframes;
using MediaBrowser.Controller.MediaEncoding;
using Microsoft.Extensions.Logging;
using Extractor = Jellyfin.MediaEncoding.Keyframes.FfProbe.FfProbeKeyframeExtractor;

/// <inheritdoc />
public partial class FfProbeKeyframeExtractor : IKeyframeExtractor
{
    private readonly IMediaEncoder _mediaEncoder;
    private readonly NamingOptions _namingOptions;
    private readonly ILogger<FfProbeKeyframeExtractor> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="FfProbeKeyframeExtractor"/> class.
    /// </summary>
    /// <param name="mediaEncoder">An instance of the <see cref="IMediaEncoder"/> interface.</param>
    /// <param name="namingOptions">An instance of <see cref="NamingOptions"/>.</param>
    /// <param name="logger">An instance of the <see cref="ILogger{FfprobeKeyframeExtractor}"/> interface.</param>
    public FfProbeKeyframeExtractor(IMediaEncoder mediaEncoder, NamingOptions namingOptions, ILogger<FfProbeKeyframeExtractor> logger)
    {
        _mediaEncoder = mediaEncoder;
        _namingOptions = namingOptions;
        _logger = logger;
    }

    /// <inheritdoc />
    public bool IsMetadataBased => false;

    /// <inheritdoc />
    public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
    {
        if (!_namingOptions.VideoFileExtensions.Contains(Path.GetExtension(filePath.AsSpan()), StringComparison.OrdinalIgnoreCase))
        {
            keyframeData = null;
            return false;
        }

        try
        {
            keyframeData = Extractor.GetKeyframeData(_mediaEncoder.ProbePath, filePath);
            return keyframeData.KeyframeTicks.Count > 0;
        }
        catch (FileNotFoundException ex)
        {
            LogKeyframeExtractionError(_logger, filePath, ex);
        }
        catch (UnauthorizedAccessException ex)
        {
            LogKeyframeExtractionError(_logger, filePath, ex);
        }
        catch (IOException ex)
        {
            LogKeyframeExtractionError(_logger, filePath, ex);
        }
        catch (InvalidDataException ex)
        {
            LogKeyframeExtractionError(_logger, filePath, ex);
        }

        keyframeData = null;
        return false;
    }

    [LoggerMessage(Level = LogLevel.Error, Message = "Extracting keyframes from {FilePath} using ffprobe failed")]
    private static partial void LogKeyframeExtractionError(ILogger logger, string filePath, Exception exception);
}
