import asyncio
import base64
import json
import time
import cv2
from global_logger import logger


class HandelTCPCommand:
    def __init__(self, camera_processors, http_client):
        self.camera_processors = camera_processors
        self.http_client = http_client

    async def capture_and_send_current_frame(self, camera_processor, message):
        """捕获当前帧并通过HTTP发送到后台"""

        cam_id = camera_processor.cam_id
        logger.info(f"摄像头 {cam_id} 准备捕获并发送当前帧")

        # 使用get_last_frame方法获取最后一帧，不直接访问内部属性
        frame = camera_processor.get_last_frame()
        if frame is None:
            logger.warning(f"摄像头 {cam_id} 没有可用的帧")
            return False

        try:
            # 将图像编码为JPEG
            success, jpg_data = cv2.imencode('.jpg', frame)
            if not success:
                logger.error(f"摄像头 {cam_id} 编码图像失败")
                return False

            def get_cap_content(message):
                map = {
                    "1": ('点1', '完成1'),
                    "2": ('点2', '完成2'),
                    "3": ('点3', '完成3'),
                    "4": ('点4', '完成4'),
                }
                return map.get(str(message).strip(), ('', ''))

            # 构建请求数据
            content, status = get_cap_content(message)
            request_data = {
                "camera_id": cam_id,
                "timestamp": time.time(),
                "image": base64.b64encode(jpg_data.tobytes()).decode('utf-8'),
                'content': content,
                "status": status
            }

            # 发送HTTP请求
            await self.http_client.send(json.dumps(request_data))
            logger.info(f"摄像头 {cam_id} 已发送当前帧到后台")
            return True
        except Exception as e:
            logger.exception(f"发送当前帧时发生错误: {e}")
            return False

    async def handle_capture_command(self, message):
        """处理TCP服务器发来的命令"""
        try:
            logger.info(f"处理TCP命令: {message}")

            # 检查是否是捕获图像的命令
            if str(message) in ['1', '2', '3', '4']:  # todo

                # 等待5秒
                logger.info(f"收到捕获图像命令，等待5秒...")
                await asyncio.sleep(5)

                # 对所有摄像头执行
                for cam_id, processor in self.camera_processors.items():
                    await self.capture_and_send_current_frame(processor, message)

                logger.info("图像捕获和发送完成")

                # 发送处理完成的响应
                response = {
                    "status": "success",
                    "timestamp": time.time(),
                    "message": "图像已成功捕获并发送"
                }
                return response
        except json.JSONDecodeError:
            logger.error(f"无法解析JSON命令: {message}")
        except Exception as e:
            logger.exception(f"处理TCP命令时出错: {e}")

        # 发送错误响应
        return {
            "status": "error",
            "timestamp": time.time(),
            "message": "处理命令时出错"
        }
