#!/usr/bin/env python3

import sys
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
from urllib.parse import unquote, urlparse
from websocket import create_connection

URL_PATH = ""
if len(sys.argv) > 1:
    URL_PATH = sys.argv[1]
    if URL_PATH.startswith('/'):
        URL_PATH = URL_PATH[1::]

WS_SERVER = f"ws://example.com:5789/{URL_PATH}"


def send_ws(payload):
    ws = create_connection(WS_SERVER)
    # res = ws.recv()
    message = unquote(payload).replace('"', '\\"')
    data = '{"version": "' + message + '"}'

    ws.send(data)
    res = ws.recv()
    ws.close()

    if res:
        return res
    return 0


def middleware_server(host_port, content_type="text/plain"):

    class CustomHandler(SimpleHTTPRequestHandler):
        def do_GET(self) -> None:
            self.send_response(200)
            try:
                payload = urlparse(self.path).query.split('=', 1)[1]
            except IndexError:
                payload = False
            if payload:
                content = send_ws(payload)
            else:
                content = "No payload specified"
            self.send_header("Content-Type", content_type)
            self.end_headers()
            self.wfile.write(content.encode())

    class _TCPServer(TCPServer):
        allow_reuse_address = True

    httpd = _TCPServer(host_port, CustomHandler)
    httpd.serve_forever()


print(f"Payload is sent to {WS_SERVER} via http://localhost:8081/?id=*")

try:
    middleware_server(('0.0.0.0', 8081))
except KeyboardInterrupt:
    pass
