using System.Diagnostics;
using System.Text.Json;

namespace TagVid.Helpers;

public class VideoMetadata
{
    public int Width { get; set; }
    public int Height { get; set; }
    public TimeSpan Duration { get; set; }
}

public class FFProbeHelper<T> where T : class
{
    private static ILogger<T> _logger;

    public FFProbeHelper(ILogger<T> logger)
    {
        _logger = logger;
    }
    public async Task<VideoMetadata?> GetVideoMetadataAsync(string filePath)
    {
        var startInfo = new ProcessStartInfo
        {
            FileName = "ffprobe",
            Arguments = $"-v quiet -print_format json -show_streams \"{filePath}\"",
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using var process = new Process { StartInfo = startInfo };
        process.Start();

        string output = await process.StandardOutput.ReadToEndAsync();
        await process.WaitForExitAsync();

        using var jsonDoc = JsonDocument.Parse(output);
        var streams = jsonDoc.RootElement.GetProperty("streams");

        var videoStream = streams.EnumerateArray()
            .FirstOrDefault(s => s.GetProperty("codec_type").GetString() == "video");

        if (videoStream.ValueKind == JsonValueKind.Undefined)
            return null;
        videoStream.TryGetProperty("duration", out var durEl1);

        _logger.LogInformation($"{videoStream.GetProperty("width")}x{videoStream.GetProperty("height")}, Duration: {durEl1}");
        var metadata = new VideoMetadata
        {
            Width = videoStream.GetProperty("width").GetInt32(),
            Height = videoStream.GetProperty("height").GetInt32(),
            Duration = durEl1.ValueKind == JsonValueKind.String
                ? TimeSpan.FromSeconds(double.Parse(durEl1.GetString() ?? "0"))
                : TimeSpan.FromSeconds(durEl1.GetDouble())
        };

        return metadata;
    }
}