using System;
using System.Collections.Generic;
using Prism.Events;
using Prism.Ioc;
using XP.Hardware.Detector.Abstractions;
using XP.Hardware.Detector.Abstractions.Enums;
using XP.Hardware.Detector.Config;
using XP.Hardware.Detector.Implementations;
using XP.Common.Logging.Interfaces;

namespace XP.Hardware.Detector.Factories
{
    /// <summary>
    /// 探测器工厂实现 | Detector factory implementation
    /// 配置驱动的探测器实例创建
    /// </summary>
    public class DetectorFactory : IDetectorFactory
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IContainerProvider _containerProvider;
        private readonly ILoggerService _logger;

        /// <summary>
        /// 构造函数 | Constructor
        /// </summary>
        /// <param name="eventAggregator">事件聚合器 | Event aggregator</param>
        /// <param name="containerProvider">Prism 容器 | Prism container</param>
        /// <param name="logger">日志服务 | Logger service</param>
        public DetectorFactory(IEventAggregator eventAggregator, IContainerProvider containerProvider, ILoggerService logger = null)
        {
            _eventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(eventAggregator));
            _containerProvider = containerProvider ?? throw new ArgumentNullException(nameof(containerProvider));
            _logger = logger?.ForModule("DetectorFactory");
        }

        /// <summary>
        /// 创建探测器实例 | Create detector instance
        /// </summary>
        public DetectorResult<IAreaDetector> CreateDetector(DetectorConfig config)
        {
            if (config == null)
            {
                var errorMsg = "配置不能为空 | Configuration cannot be null";
                _logger?.Error(null, errorMsg);
                return DetectorResult<IAreaDetector>.Failure(errorMsg);
            }

            try
            {
                _logger?.Info($"开始创建探测器，类型：{config.Type} | Starting to create detector, type: {config.Type}");

                IAreaDetector detector = config.Type switch
                {
                    DetectorType.Varex => CreateVarexDetector(config),
                    //DetectorType.IRay => CreateIRayDetector(config),
                    DetectorType.Hamamatsu => throw new NotImplementedException("Hamamatsu 探测器尚未实现 | Hamamatsu detector not implemented yet"),
                    _ => throw new NotSupportedException($"不支持的探测器类型：{config.Type} | Unsupported detector type: {config.Type}")
                };

                // 注册到容器（通过 IContainerExtension 注册实例）| Register to container
                var containerExtension = _containerProvider.Resolve<IContainerExtension>();
                containerExtension.RegisterInstance<IAreaDetector>(detector);
                _logger?.Debug("探测器实例已注册到容器 | Detector instance registered to container");

                _logger?.Info($"探测器创建成功，类型：{config.Type} | Detector created successfully, type: {config.Type}");
                return DetectorResult<IAreaDetector>.Success(detector, "探测器创建成功 | Detector created successfully");
            }
            catch (NotImplementedException ex)
            {
                var errorMsg = $"探测器类型尚未实现 | Detector type not implemented: {ex.Message}";
                _logger?.Warn(errorMsg);
                return DetectorResult<IAreaDetector>.Failure(errorMsg, ex, -2);
            }
            catch (NotSupportedException ex)
            {
                var errorMsg = $"不支持的探测器类型 | Unsupported detector type: {ex.Message}";
                _logger?.Error(ex, errorMsg);
                return DetectorResult<IAreaDetector>.Failure(errorMsg, ex, -3);
            }
            catch (Exception ex)
            {
                var errorMsg = $"创建探测器失败 | Failed to create detector: {ex.Message}";
                _logger?.Error(ex, errorMsg);
                return DetectorResult<IAreaDetector>.Failure(errorMsg, ex, -1);
            }
        }

        /// <summary>
        /// 创建 Varex 探测器 | Create Varex detector
        /// </summary>
        private IAreaDetector CreateVarexDetector(DetectorConfig config)
        {
            var varexConfig = config as VarexDetectorConfig
                ?? throw new ArgumentException("Varex 探测器需要 VarexDetectorConfig | Varex detector requires VarexDetectorConfig");

            _logger?.Debug($"创建 Varex 探测器实例，Binning 模式：{varexConfig.BinningMode}，增益模式：{varexConfig.GainMode} | Creating Varex detector instance, Binning mode: {varexConfig.BinningMode}, Gain mode: {varexConfig.GainMode}");
            return new VarexDetector(varexConfig, _eventAggregator, _logger);
        }

        ///// <summary>
        ///// 创建 iRay 探测器 | Create iRay detector
        ///// </summary>
        //private IAreaDetector CreateIRayDetector(DetectorConfig config)
        //{
        //    var irayConfig = config as IRayDetectorConfig
        //        ?? throw new ArgumentException("iRay 探测器需要 IRayDetectorConfig | iRay detector requires IRayDetectorConfig");

        //    return new IRayDetector(irayConfig, _eventAggregator);
        //}

        /// <summary>
        /// 获取支持的探测器类型 | Get supported detector types
        /// </summary>
        public IEnumerable<DetectorType> GetSupportedTypes()
        {
            return new[] { DetectorType.Varex, DetectorType.IRay };
        }
    }
}
