import json
import logging
from http.server import BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
    def __init__(self, custom_func, driver, logger, socket_url, socket_port, *args, **kwargs):
        self._custom_func = custom_func
        self.logger = logger
        self.driver = driver
        self._socket_url = socket_url
        self._socket_port = socket_port
        super().__init__(*args, **kwargs)
        
    def do_POST(self):
        if self.path == '/webrtc-internals-exporter':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            self.logger.log(logging.DEBUG, f"POST request,\nPath: {self.path}\nHeaders:\n{self.headers}\n\nBody:\n{post_data.decode('utf-8')}")
            self._custom_func(self.driver, json.loads(post_data.decode('utf-8')), self._socket_url, self._socket_port)
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b'POST request received')
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'404 Not Found')
            
    def do_GET(self):
        if self.path == '/heartbeat':
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b'Heartbeat OK')
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'404 Not Found')