from __future__ import print_function
import json
import logging
import os
import threading
try:
    from http.server import BaseHTTPRequestHandler, HTTPServer
    from socketserver import ThreadingMixIn
except ImportError:
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
    from SocketServer import ThreadingMixIn

LOG = logging.getLogger(__name__)


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    daemon_threads = True


def start_web(config, runtime_dir, package_dir):
    if not config.get("enabled", True):
        return None
    static_dir = os.path.join(package_dir, "web")

    class Handler(BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            LOG.debug("Web: " + fmt, *args)

        def do_GET(self):
            path = self.path.split("?", 1)[0]
            if path == "/api/status":
                return self._file(os.path.join(runtime_dir, "status.json"), "application/json", fallback=b'{"status":"starting"}')
            if path in ("/", "/index.html"):
                return self._file(os.path.join(static_dir, "index.html"), "text/html; charset=utf-8")
            if path == "/logo.png":
                return self._file(os.path.join(static_dir, "logo.png"), "image/png")
            self.send_error(404)

        def _file(self, path, content_type, fallback=None):
            try:
                with open(path, "rb") as handle:
                    data = handle.read()
            except IOError:
                if fallback is None:
                    self.send_error(404)
                    return
                data = fallback
            self.send_response(200)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(data)))
            self.send_header("Cache-Control", "no-store" if "json" in content_type else "public, max-age=3600")
            self.end_headers()
            self.wfile.write(data)

    server = ThreadedHTTPServer((config.get("bind", "127.0.0.1"), int(config.get("port", 8765))), Handler)
    thread = threading.Thread(target=server.serve_forever, name="br-skywarn-web")
    thread.daemon = True
    thread.start()
    LOG.info("Status dashboard listening on http://%s:%s", config.get("bind"), config.get("port"))
    return server
