import socket
import json
import struct
from json import JSONEncoder
from conf.config import exists


def parse_request(client_socket: socket.socket):
    request_header_size = struct.unpack("!Q", read_bytes(client_socket, 8))[0]
    request_map = json.JSONDecoder().decode(read_bytes(client_socket, request_header_size).decode("utf-8"))
    return request_map


def generate_response(response):
    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

    return response_binary


def read_bytes(s: 'socket.socket', size: 'int') -> 'bytes':
    data = ''.encode('utf-8')
    while len(data) < size:
        rsp_data = s.recv(size - len(data))
        data += rsp_data
        if len(rsp_data) == 0:
            break
    return data


def check(cookie: str):
    if exists(cookie):
        return cookie
    return None  # TODO: if user error, return None, else return cookie
    pass


def generate_request(request) -> 'bytes':
    """
    根据传入的dict生成请求
    请求包含 8字节头长度+头数据
    :param request: dict
    :return: bytes 请求数据
    """
    request_bytes = JSONEncoder().encode(request).encode("utf-8")
    return struct.pack("!Q", len(request_bytes)) + request_bytes
