import toml
import threading
from loguru import logger
import logging
import zmq
from infer import Lane_model_infer
import numpy as np
import cv2


lock = threading.Lock()
response = {'code': 0, 'data': 0}




# 处理 server 响应数据
def server_resp(lane_infer_port):
    global response
    logger.info("lane server thread init success")
    
    context = zmq.Context()
    # 启动 server
    socket = context.socket(zmq.REP)
    socket.bind(f"tcp://*:{lane_infer_port}")
    logger.info("lane infer server init success")
    while True:
        message = socket.recv_string()
        with lock:
            socket.send_pyobj(response)


def lane_infer_server_main(queue):

    context2 = zmq.Context()
    socket_server = context2.socket(zmq.PUB)
    socket_server.setsockopt(zmq.SNDHWM,10)
    socket_server.bind("tcp://*:7778")

    if queue != None:
        class Handler(logging.Handler):
            def emit(self, record):
                log_entry = self.format(record)
                queue.put({'level': record.levelname.lower(), 'content': log_entry})
        # logger.remove()
        handler = Handler()
        logger.add(handler, format="{time:MM-DD HH:mm:ss} {message}", level="DEBUG")

    cfg = toml.load('/home/evan/Workplace/project_infer/cfg_infer_server.toml')

    # 配置日志输出
    logger.add(cfg['debug']['logger_filename'], format=cfg['debug']['logger_format'], retention = 5, level="INFO")

    # 连接摄像头 server 巡线只需要连接前摄像头
    context = zmq.Context()
    camera_socket = context.socket(zmq.REQ)
    camera_socket.connect(f"tcp://localhost:{cfg['camera']['front_camera_port']}")
    logger.info("connect camera success")

    # 初始化 paddle 推理器
    predictor = Lane_model_infer()
    logger.info("lane model load success")
    # 启动 lane_infer_server 线程
    mythread = threading.Thread(target=server_resp,
                                args=(cfg['server']['lane_infer_port'],),
                                daemon=True)
    
    mythread.start()
    import signal
    import sys
    def signal_handler(signum, frame):
        logger.info("Received signal, exiting...")
        camera_socket.close()
        context.term()
        sys.exit(0)

    # 注册信号处理函数
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)


    while True:
        camera_socket.send_string("")
        message = camera_socket.recv()
        np_array = np.frombuffer(message, dtype=np.uint8)
        frame = cv2.imdecode(np_array, cv2.IMREAD_COLOR)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        result = predictor.infer(frame)
        with lock:
            response['data'] = result
        # print(result)
        cv2.circle(frame,(int(result[0]),int(result[1])),5,(0,255,0),-1)
        cv2.putText(frame, f"{int(result[0]) - 160}", (0,25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 2, cv2.LINE_AA)
        socket_server.send_pyobj(frame)
        if cv2.waitKey(1) == 27:
            break
    mythread.join()
    logger.info("lane infer server exit")

if __name__ == "__main__":
    lane_infer_server_main(None)