// <copyright file="MatroskaKeyframeExtractor.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 Jellyfin.MediaEncoding.Keyframes;
using Microsoft.Extensions.Logging;
using Extractor = Jellyfin.MediaEncoding.Keyframes.Matroska.MatroskaKeyframeExtractor;

/// <inheritdoc />
public partial class MatroskaKeyframeExtractor : IKeyframeExtractor
{
    private readonly ILogger<MatroskaKeyframeExtractor> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="MatroskaKeyframeExtractor"/> class.
    /// </summary>
    /// <param name="logger">An instance of the <see cref="ILogger{MatroskaKeyframeExtractor}"/> interface.</param>
    public MatroskaKeyframeExtractor(ILogger<MatroskaKeyframeExtractor> logger)
    {
        _logger = logger;
    }

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

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

        try
        {
            keyframeData = Extractor.GetKeyframeData(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 matroska metadata failed")]
    private static partial void LogKeyframeExtractionError(ILogger logger, string filePath, Exception exception);
}
