using System.Diagnostics;

namespace SirayaPrinter.Sync;

public static class ServiceControl
{
    private const string ServiceName = "SirayaPrinterService";

    public static void Stop()
    {
        RunNet($"stop {ServiceName}", ignoreErrors: true);
        Thread.Sleep(2000);
    }

    public static void Start()
    {
        var code = RunNet($"start {ServiceName}", ignoreErrors: false);
        if (code != 0)
            throw new InvalidOperationException($"Failed to start {ServiceName} (exit {code})");
    }

    public static void Restart()
    {
        Stop();
        Start();
    }

    private static int RunNet(string args, bool ignoreErrors)
    {
        var psi = new ProcessStartInfo
        {
            FileName = "net.exe",
            Arguments = args,
            UseShellExecute = false,
            CreateNoWindow = true,
        };
        using var proc = Process.Start(psi) ?? throw new InvalidOperationException("Could not start net.exe");
        proc.WaitForExit();
        if (!ignoreErrors && proc.ExitCode != 0)
            return proc.ExitCode;
        return proc.ExitCode;
    }
}
