using System;
using System.ServiceProcess;
using System.Threading;
using CncService.Interface;

namespace CncService.Impl
{
    /// <summary>
    /// Windows 服务检测实现（基于 ServiceController）
    /// </summary>
    public class WindowsServiceChecker : IWindowsServiceChecker
    {
        public ServiceStatusEnum GetServiceStatus(string serviceName)
        {
            try
            {
                using (var sc = new ServiceController(serviceName))
                {
                    sc.Refresh();
                    switch (sc.Status)
                    {
                        case ServiceControllerStatus.Running:
                            return ServiceStatusEnum.Running;
                        case ServiceControllerStatus.StartPending:
                        case ServiceControllerStatus.ContinuePending:
                            return ServiceStatusEnum.Starting;
                        case ServiceControllerStatus.Stopped:
                        case ServiceControllerStatus.StopPending:
                        case ServiceControllerStatus.PausePending:
                        case ServiceControllerStatus.Paused:
                            return ServiceStatusEnum.Stopped;
                        default:
                            return ServiceStatusEnum.Starting;
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // 服务未安装
                return ServiceStatusEnum.NotInstalled;
            }
            catch
            {
                // 其他异常视为不可用，保守处理
                return ServiceStatusEnum.NotInstalled;
            }
        }

        public (bool Success, string Message) TryStartService(string serviceName, int timeoutSeconds)
        {
            try
            {
                using (var sc = new ServiceController(serviceName))
                {
                    sc.Refresh();
                    if (sc.Status == ServiceControllerStatus.Running)
                        return (true, "已运行");

                    sc.Start();
                    var timeout = TimeSpan.FromSeconds(timeoutSeconds);
                    var sw = System.Diagnostics.Stopwatch.StartNew();
                    while (sw.Elapsed < timeout)
                    {
                        sc.Refresh();
                        if (sc.Status == ServiceControllerStatus.Running)
                            return (true, "启动成功");
                        Thread.Sleep(500);
                    }
                    return (false, $"启动超时，当前状态={sc.Status}");
                }
            }
            catch (InvalidOperationException)
            {
                return (false, "NotInstalled");
            }
            catch (Exception ex)
            {
                return (false, $"启动失败: {ex.Message}");
            }
        }

        public (bool Success, string Message) TryStopService(string serviceName, int timeoutSeconds)
        {
            try
            {
                using (var sc = new ServiceController(serviceName))
                {
                    sc.Refresh();
                    if (sc.Status == ServiceControllerStatus.Stopped)
                        return (true, "已停止");

                    sc.Stop();
                    var timeout = TimeSpan.FromSeconds(timeoutSeconds);
                    var sw = System.Diagnostics.Stopwatch.StartNew();
                    while (sw.Elapsed < timeout)
                    {
                        sc.Refresh();
                        if (sc.Status == ServiceControllerStatus.Stopped)
                            return (true, "停止成功");
                        Thread.Sleep(500);
                    }
                    return (false, $"停止超时，当前状态={sc.Status}");
                }
            }
            catch (InvalidOperationException)
            {
                return (false, "NotInstalled");
            }
            catch (Exception ex)
            {
                return (false, $"停止失败: {ex.Message}");
            }
        }
    }
}
