import socket
import threading
import json
import struct
from loguru import logger
from dcs.tests.spider import Spider


class RequestHandler(threading.Thread):
    def __init__(self, file_server: 'FileServer', client_socket: 'socket.socket', request_map: 'dict'):
        super().__init__()
        self.file_server = file_server
        self.client_socket = client_socket
        self.request_map = request_map
        self.daemon = True
        pass

    def run(self) -> None:
        try:
            if self.request_map['action'] == 'test':
                logger.info(f"[REQUEST] test")
                response = {
                    'test': 'hello TEST'
                }
                response_binary = json.JSONEncoder().encode(response).encode("utf-8")
                response_binary_len = len(response_binary)
                response_binary_len_binary = struct.pack("!Q", response_binary_len)

                response_binary = response_binary_len_binary + response_binary
                self.client_socket.sendall(response_binary)
                logger.info(f"[RESPONSE] test: {response['test']}, header size: {response_binary_len}")
            elif self.request_map['action'] == 'translate':
                logger.info(f"[REQUEST] translate")
                spider = Spider(self.request_map['word'])
                response = {
                    'translate': spider.run()
                }
                response_binary = json.JSONEncoder().encode(response).encode("utf-8")
                response_binary_len = len(response_binary)
                response_binary_len_binary = struct.pack("!Q", response_binary_len)

                response_binary = response_binary_len_binary + response_binary
                self.client_socket.sendall(response_binary)
                logger.info(f"[RESPONSE] translate: {response['translate']}, header size: {response_binary_len}")
            elif self.request_map['action'] == 'crawl zhiwang':
                logger.info(f"[REQUEST] crawl zhiwang")
                spider = Spider(self.request_map['word'])
                response = {
                    'crawl zhiwang': spider.run()
                }
                response_binary = json.JSONEncoder().encode(response).encode("utf-8")
                response_binary_len = len(response_binary)
                response_binary_len_binary = struct.pack("!Q", response_binary_len)

                response_binary = response_binary_len_binary + response_binary
                self.client_socket.sendall(response_binary)
                logger.info(f"[RESPONSE] crawl zhiwang: {response['crawl zhiwang']}, header size: {response_binary_len}")
        finally:
            self.client_socket.close()
