from urllib.parse import urlparse, parse_qs
from http.server import HTTPServer, BaseHTTPRequestHandler
import threading

from tools.log import logger


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def log_message(self, format, *args):
        # 禁用默认的控制台日志输出
        return

    def do_GET(self):
        parsed_url = urlparse(self.path)
        query_params = parse_qs(parsed_url.query)

        p = query_params.get('xxx', [''])[0]
        p_list = p.split('----')

        logger.info(f'[脚本][模拟器-{p_list[0]}]-{p_list[1]}-{p_list[2]}-{p_list[3]}-{p_list[4]}-{p_list[5]}',int(p_list[0]))

        response = b'{"message": "ok"}'
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Content-Length', str(len(response)))
        self.end_headers()
        self.wfile.write(response)


def start_http(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port = 8000):
    server_address = ('', port + 1)
    httpd = server_class(server_address, handler_class)
    httpd_thread = threading.Thread(target=httpd.serve_forever)
    httpd_thread.daemon = True
    httpd_thread.start()
    return httpd


def stop_http(httpd):
    httpd.shutdown()
    httpd.server_close()
