using OpenCvSharp;
namespace SHH.CameraSdk
{
    /// <summary>
    /// [图像缩放服务]
    /// 实现：基于基类，专注于将原图缩放并挂载到 TargetMat
    /// </summary>
    public class ImageScaleCluster : BaseFrameProcessor<ScaleWorker>
    {
        public ImageScaleCluster(int count, ProcessingConfigManager configManager)
            : base(count, "ScaleCluster", configManager)
        {
        }

        protected override ScaleWorker CreateWorker(int id) => new ScaleWorker(this, _configManager);
    }

    public class ScaleWorker : BaseWorker
    {
        private readonly ImageScaleCluster _parent;
        private readonly ProcessingConfigManager _configManager;

        public ScaleWorker(ImageScaleCluster parent, ProcessingConfigManager configManager)
        {
            _parent = parent;
            _configManager = configManager;
        }

        protected override void PerformAction(long deviceId, SmartFrame frame, FrameDecision decision)
        {
            // 1. 获取实时配置 (极快，内存读取)
            var options = _configManager.GetOptions(deviceId);

            Mat sourceMat = frame.InternalMat;
            if (sourceMat.Empty()) return;

            // 2. 原始尺寸
            int srcW = sourceMat.Width;
            int srcH = sourceMat.Height;

            // 3. 目标尺寸
            int targetW = options.TargetWidth;
            int targetH = options.TargetHeight;

            // 4. 判断是否需要缩放
            bool needResize = false;

            // 场景 A: 原始图比目标大，且允许缩小
            if (options.EnableShrink && (srcW > targetW || srcH > targetH))
            {
                needResize = true;
            }
            // 场景 B: 原始图比目标小，且允许放大 (通常为 False)
            else if (options.EnableExpand && (srcW < targetW || srcH < targetH))
            {
                needResize = true;
            }

            // 5. 执行动作
            if (needResize)
            {
                Mat targetMat = new Mat();
                // 线性插值
                Cv2.Resize(frame.InternalMat, targetMat, new Size(targetW, targetH), 0, 0, InterpolationFlags.Linear);

                // 挂载
                var scaleType = (srcW > targetW) ? FrameScaleType.Shrink : FrameScaleType.Expand;
                frame.AttachTarget(targetMat, scaleType);
            }
            else
            {
                // [透传] 不需要缩放
                // 此时 frame.TargetMat 为 null，代表“无变化”
            }
        }

        protected override void NotifyFinished(long did, SmartFrame frame, FrameDecision dec)
        {
            _parent.PassToNext(did, frame, dec);
        }
    }
}