import socket
from collections import deque


# from dcs.tests.spider import Spider
# from dcs.tests.requester import Requester
# from dcs.tests.user_process import UP
# from dcs.tests.response import Responser


class CUI:
    def __init__(self, user_name, login_time, login_state, state, cookie, st=None):
        self.user_name = user_name
        self.login_time = login_time
        self.login_state = login_state
        self.state = state
        self.cookie = cookie
        self.socket = st
        self.crawl_result = deque()


class global_var:
    """需要定义全局变量的放在这里"""
    free_spiders = []
    current_user_info: list[CUI] = []
    requester = None
    server = None
    spider = None
    up = None
    communicator = None
    server_socket = None


def get_free_sockets() -> tuple[socket.socket]:
    fs: list[socket.socket] = []
    for i in global_var.current_user_info:
        if i.state == 'free':
            fs.append(i.socket)
    return tuple(fs)


def exists(cookie):
    for i in global_var.current_user_info:
        if i.cookie == cookie:
            return True
    return False


def add_user(user_name, login_time, login_state, state, cookie, st=None):
    global_var.current_user_info.append(CUI(user_name, login_time, login_state, state, cookie, st))


def set_state_socket(sockett, state):
    for i in global_var.current_user_info:
        if i.socket == sockett:
            i.state = state
            break


def set_crawl_result(cookie, result):
    for i in global_var.current_user_info:
        if i.cookie == cookie:
            i.crawl_result.append(result)
            # print(f'hhh: {cookie}', result)
            break


def get_crawl_result(cookie):
    for i in global_var.current_user_info:
        if i.cookie == cookie:
            # print(f'hgf: {cookie}', i.crawl_result)
            return i.crawl_result


def get_by_cookie(cookie):
    for i in global_var.current_user_info:
        if i.cookie == cookie:
            return i
    return None


def delete_user(cookie):
    i = get_by_cookie(cookie)
    global_var.current_user_info.remove(i)
