import socket
import threading

from loguru import logger
from dcs.tools.message_process import parse_request, check
from conf.config import global_var


class RequestHandler(threading.Thread):
    def __init__(self, client_socket: 'socket.socket'):
        super().__init__()
        self.client_socket = client_socket

    def run(self) -> None:
        try:
            while True:
                request_map = parse_request(self.client_socket)

                if request_map['action'] == 'end':
                    logger.info(f"[REQUEST] end")
                    logger.debug(f"communication over from {self.client_socket.getpeername()}!")
                    break
                elif request_map['action'] == 'crawl zhiwang':
                    chk_res = check(request_map['cookie'])
                    if chk_res is None:
                        logger.warning("user info error!")
                        break
                    global_var.spider.add_task(request_map, self.client_socket)
                elif request_map['action'] in ['report_free', 'login', 'register']:
                    global_var.up.add_request(request_map, self.client_socket)
        except Exception as e:
            print(str(e))
