using System.Diagnostics;
using Microsoft.Extensions.Logging;
using PSLauncher.Models;
using SysProcess = System.Diagnostics.Process;

namespace PSLauncher.Core.Process;

public sealed class ProcessLauncher : IProcessLauncher
{
    private readonly ILogger<ProcessLauncher> _logger;

    public ProcessLauncher(ILogger<ProcessLauncher> logger) => _logger = logger;

    public SysProcess Launch(InstalledVersion version, string[]? args = null)
    {
        if (!File.Exists(version.ExecutablePath))
            throw new FileNotFoundException("Executable not found", version.ExecutablePath);

        var psi = new ProcessStartInfo
        {
            FileName = version.ExecutablePath,
            WorkingDirectory = version.FolderPath,
            UseShellExecute = true
        };
        if (args is not null)
        {
            foreach (var arg in args) psi.ArgumentList.Add(arg);
        }

        _logger.LogInformation("Launching {Exe}", version.ExecutablePath);
        return SysProcess.Start(psi)
               ?? throw new InvalidOperationException("Process.Start returned null");
    }

    public bool IsRunning(InstalledVersion version)
    {
        var name = Path.GetFileNameWithoutExtension(version.ExecutablePath);
        return SysProcess.GetProcessesByName(name).Any(p =>
        {
            try { return string.Equals(p.MainModule?.FileName, version.ExecutablePath, StringComparison.OrdinalIgnoreCase); }
            catch { return false; }
        });
    }
}
