using System.Diagnostics;
using System.IO;

namespace ytLive.Services.Encoder;

/// <summary>
/// The real <see cref="IEncoderProcess"/>: a <see cref="Process"/> with all three
/// std streams redirected. Constructed by <see cref="FfmpegEncoder"/> for both the
/// encoder subprocess and the <c>-encoders</c> probe.
/// </summary>
public sealed class FfmpegEncoderProcess : IEncoderProcess
{
    private readonly Process _process;

    public FfmpegEncoderProcess() => _process = new Process { EnableRaisingEvents = true };

    public void Start(ProcessStartInfo startInfo)
    {
        _process.StartInfo = startInfo;
        _process.Start();
    }

    public Stream StandardInput => _process.StandardInput.BaseStream;
    public TextReader StandardOutput => _process.StandardOutput;
    public TextReader StandardError => _process.StandardError;

    public bool HasExited => _process.HasExited;
    public int ExitCode => _process.ExitCode;
    public void Kill()
    {
        if (!_process.HasExited) _process.Kill();
    }

    public Task WaitForExitAsync(CancellationToken cancellationToken = default)
        => _process.WaitForExitAsync(cancellationToken);

    public void Dispose() => _process.Dispose();
}
