import socket
import threading
import conf.config as config
import dcs.tools.database as database
from loguru import logger
from conf.config import global_var


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

    def report_state(self, state):
        logger.info(f"[REQUEST] report free")
        config.set_state_socket(self.client_socket, state)
        response = {
            'report_free': 'success marked ' + str(self.request_map['cookie'])
        }
        # self.client_socket.sendall(generate_response(response))
        global_var.communicator.add_response('report_free', self.client_socket, response)
        logger.info(f"[RESPONSE] report free: {response['report_free']}")

    def login(self, user, password, st):
        logger.info(f"[REQUEST] login")
        database.mysql_conn()
        response = database.login(user, password, st)
        response = {
            'cookie': response
        }
        # self.client_socket.sendall(generate_response(response))
        global_var.communicator.add_response('cookie', self.client_socket, response)
        logger.info(f"[RESPONSE] cookie: {response['cookie']}")

    def register(self, user, password):
        logger.info(f"[REQUEST] register")
        database.mysql_conn()
        response = database.register(user, password)
        response = {
            'register': response
        }
        # self.client_socket.sendall(generate_response(response))
        global_var.communicator.add_response('register', self.client_socket, response)
        logger.info(f"[RESPONSE] register: {response['register']}")

    def run(self) -> None:
        if self.request_map['action'] == 'report_free':
            self.report_state('free')
        elif self.request_map['action'] == 'login':
            self.login(self.request_map['user'], self.request_map['password'], self.client_socket)
        elif self.request_map['action'] == 'register':
            self.register(self.request_map['user'], self.request_map['password'])
        else:
            self.client_socket.close()
