import socket
import json
import threading
import time
from .BaseVR import BaseVR

"""
TCP局域网直连的头显设备
"""

class VRSocket(BaseVR):
    # 定义需要的配置字段为静态字段
    name = "TCP Socket 头显"
    description = "使用TCP Socket连接的VR设备"
    need_config = {
        "ip": {
            "type": "string",
            "description": "服务器IP地址"
        },
        "port": {
            "type": "integer",
            "description": "服务器端口号",
            "default": 12345
        }
    }
    
    def __init__(self, config=None):
        super().__init__(config)
        
        # 初始化 socket 连接相关变量
        self.ip = None
        self.port = None
        self.sock = None
        self.receiver_thread = None
        self.polling_thread = None
        self.reconnect_interval = 1  # 重连间隔秒数
        
        # 设置事件回调
        self._events.update({
             "connect": self._default_connect_callback,
             "disconnect": self._default_disconnect_callback,
             "error": self._default_error_callback
        })
        
        # 如果提供了配置，则设置配置
        if config:
            self.set_config(config)

    
    def _default_connect_callback(self):
        """默认连接回调"""
        print(f"[VR连接]: 已连接到 Unity 服务器 {self.ip}:{self.port}")

    def _default_disconnect_callback(self, msg=""):
        """默认断开连接回调"""
        print(f"[VR断开连接]: {msg}")

    def _default_error_callback(self, error_msg):
        """默认错误回调"""
        print(f"[VR错误]: {error_msg}")

    

    def _main(self):
        """
        Socket 接收线程
        """
        buffer = ""
        while True:
            try:
                # 检查socket是否仍然连接
                if self.sock is None or self.get_conn_status() != 1:
                    break
                    
                data = self.sock.recv(1024)
                if not data:
                    self.emit("disconnect", "[Quest断开连接]")
                    self.set_conn_status(2)
                    break
                buffer += data.decode('utf-8')
                while '\n' in buffer:
                    line, buffer = buffer.split('\n', 1)
                    if line.strip() == "":
                        continue
                    try:
                        msg = json.loads(line)
                        self.emit("message", msg)
                    except json.JSONDecodeError as e:
                        self.emit("error", f"[JSON解析失败]: {e}")
                        break
            except Exception as e:
                if self.get_conn_status() == 1:  # 只有在连接状态时才报告异常
                    self.emit("error", f"Socket接收异常: {e}")
                    self.set_conn_status(2)
                break

    def _connect_device(self):
        """
        建立到VR设备的Socket连接
        """
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.sock.connect((self.ip, self.port))
            self.emit("connect")
            return True
        except Exception as e:
            self.emit("error", f"连接失败: {e}")
            return False
        
    def _disconnect_device(self):
        """
        断开与VR设备的Socket连接
        """
        if self.sock:
            self.sock.close()
            self.sock = None
            self.emit("disconnect", "[VR断开连接]")
        return True
        
    def set_config(self, config):
        """
        设置设备配置，验证配置是否符合need_config要求
        :param config: 配置字典
        :return: 是否设置成功
        """
        # 检查必需的配置字段
        for key in self.need_config:
            if key not in config:
                raise ValueError(f"缺少必需的配置字段: {key}")
        
        self.config = config
        self.ip = config["ip"]
        self.port = int(config["port"])
        
        return True