using System;
using System.ServiceProcess;
using CncCollector.Api;
using CncCollector.Config;
using CncCollector.Core;
using log4net;

namespace CncCollector
{
    /// <summary>
    /// CNC机床数据采集 Windows Service 包装类。
    /// 将 CollectorEngine 和 CollectorApiServer 的生命周期绑定到 Windows Service 控制。
    /// </summary>
    public class CncCollectorService : ServiceBase
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(CncCollectorService));

        private CollectorEngine _engine;
        private CollectorApiServer _apiServer;
        private CollectorConfig _config;

        /// <summary>
        /// 服务名称常量，与 sc.exe / NSSM 注册名一致
        /// </summary>
        public const string ServiceNameConst = "CncCollector";

        /// <summary>
        /// 初始化服务实例，配置服务能力
        /// </summary>
        public CncCollectorService()
        {
            base.ServiceName = ServiceNameConst;
            CanPauseAndContinue = true;
            CanShutdown = true;
            CanStop = true;
            AutoLog = true;
        }

        /// <summary>
        /// 服务启动：加载配置、启动引擎和API
        /// </summary>
        protected override void OnStart(string[] args)
        {
            _log.Info("Windows Service OnStart 触发");

            try
            {
                // 加载配置
                _config = CollectorConfig.Load();
                _log.Info("配置文件加载成功");
            }
            catch (Exception ex)
            {
                _log.Fatal("加载配置文件失败，服务无法启动", ex);
                throw;
            }

            // 从数据库加载运行时配置
            try
            {
                ConfigLoader.LoadRuntimeConfig(_config.BusinessConnection, _config);
            }
            catch (Exception ex)
            {
                _log.Warn("从数据库加载配置失败，使用文件默认值", ex);
            }

            // 创建并启动引擎
            _engine = new CollectorEngine(_config);
            _engine.Start();

            // 创建并启动管理API
            _apiServer = new CollectorApiServer(_engine, _config.ApiKey, _config.ApiPort);
            _apiServer.Start();

            _log.Info($"采集服务已启动，管理API: http://localhost:{_config.ApiPort}/api/collector/status");
        }

        /// <summary>
        /// 服务停止：优雅关闭引擎和API
        /// </summary>
        protected override void OnStop()
        {
            _log.Info("Windows Service OnStop 触发，开始优雅关闭...");

            try
            {
                _apiServer?.Stop();
            }
            catch (Exception ex)
            {
                _log.Error("停止管理API异常", ex);
            }

            try
            {
                _engine?.Stop();
            }
            catch (Exception ex)
            {
                _log.Error("停止采集引擎异常", ex);
            }

            _log.Info("采集服务已停止");
        }

        /// <summary>
        /// 服务暂停：停止引擎（保留配置，不释放资源）
        /// </summary>
        protected override void OnPause()
        {
            _log.Info("Windows Service OnPause 触发");

            try
            {
                _engine?.Stop();
                _log.Info("采集引擎已暂停");
            }
            catch (Exception ex)
            {
                _log.Error("暂停采集引擎异常", ex);
            }
        }

        /// <summary>
        /// 服务恢复：重新启动引擎
        /// </summary>
        protected override void OnContinue()
        {
            _log.Info("Windows Service OnContinue 触发");

            try
            {
                if (_engine != null && !_engine.IsRunning)
                {
                    _engine.Start();
                    _log.Info("采集引擎已恢复运行");
                }
            }
            catch (Exception ex)
            {
                _log.Error("恢复采集引擎异常", ex);
            }
        }

        /// <summary>
        /// 系统关机时：快速关闭
        /// </summary>
        protected override void OnShutdown()
        {
            _log.Info("系统关机，采集服务正在关闭...");
            OnStop();
        }
    }
}
