#!/usr/bin/env python3
import json
import ssl
import threading
from pathlib import Path
from http.server import BaseHTTPRequestHandler, HTTPServer

HOST = "127.0.0.1"
HTTP_PORT = 9080
HTTPS_PORT = 9449
CERT = "/home/teknari/.ssl_for_local_servers/cert.pem"
KEY = "/home/teknari/.ssl_for_local_servers/key.pem"


HTML_FILE = Path("./didactyl.html")


class Handler(BaseHTTPRequestHandler):
    def _cors(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.send_header("Access-Control-Allow-Private-Network", "true")

    def do_OPTIONS(self):
        self.send_response(204)
        self._cors()
        self.end_headers()

    def do_GET(self):
        if self.path in ("/", "/didactyl.html") and HTML_FILE.exists():
            body = HTML_FILE.read_bytes()
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self._cors()
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return

        body = json.dumps(
            {
                "success": True,
                "name": "python-test",
                "path": self.path,
                "scheme_hint": "https" if self.server.server_port == HTTPS_PORT else "http",
            }
        ).encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self._cors()
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):
        print(f"[{self.server.server_port}] " + (fmt % args), flush=True)


httpd = HTTPServer((HOST, HTTP_PORT), Handler)
httpsd = HTTPServer((HOST, HTTPS_PORT), Handler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(certfile=CERT, keyfile=KEY)
httpsd.socket = ctx.wrap_socket(httpsd.socket, server_side=True)

print(f"HTTP  listening on http://{HOST}:{HTTP_PORT}", flush=True)
print(f"HTTPS listening on https://{HOST}:{HTTPS_PORT}", flush=True)
print("Use Ctrl+C to stop", flush=True)

threading.Thread(target=httpd.serve_forever, daemon=True).start()
httpsd.serve_forever()
