import http.server
import threading
import webbrowser
import importlib.resources
from functools import partial
import json


def get_frontend_path():
    return str(importlib.resources.files("dep_orbits").joinpath("frontend-dist"))


class RequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, data, **kwargs) -> None:
        self.data = data
        super().__init__(*args, **kwargs)

    def do_GET(self):
        if self.path.startswith("/data"):
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            self.wfile.write(bytes(json.dumps(self.data), encoding="utf-8"))
        else:
            super().do_GET()


def start_server(data) -> threading.Thread:
    print(data)
    PORT = 8080
    web_dir = get_frontend_path()

    handler = partial(RequestHandler, directory=web_dir, data=data)

    server = http.server.ThreadingHTTPServer(("127.0.0.1", PORT), handler)

    print(f"Serving frontend from: {web_dir}")
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    webbrowser.open(f"http://localhost:{PORT}/index.html")

    return thread
