from jupyter_dash import JupyterDash as Dash
import dash_bootstrap_components as dbc
from src.callbacks import register_callbacks


class Appli:
    def __init__(self, layout, data):
        server_url, host, port, proxy, base_path = self._get_tl_config()
        app = Dash(
            server_url=server_url, 
            requests_pathname_prefix=base_path,
        )
        app.layout = layout
        app.data = data
        register_callbacks(app)
        app.run_server(mode="inline", host=host, port=port, proxy=proxy)

        
    def _get_tl_config(self):
        import socket, errno, os
        # Find a free port
        host = "0.0.0.0"
        port = 8050
        end = 9999
        found = False
        while not found:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                try:
                    s.bind((host, port))
                    found = True
                except socket.error as e:
                    if e.errno == errno.EADDRINUSE:
                        port = port + 1
                        if (port > end):
                            raise "No available APP port"
                    else:
                        raise e
        if (os.getenv("HOST", None) is not None):
            proto = os.getenv("PROTO")
            actualhost = os.getenv("JUPYTER_HOST", os.getenv("VOILA_HOST", ""))
            localport = os.getenv("PORT", 80)
            intermediatehost = os.getenv("HOST", "localhost")
            base_path = f"/{actualhost}/app_proxy/{port}/"
            proxified= f"{proto}://{intermediatehost}:{localport}{base_path}"
            localurl = f"http://{host}:{port}"
            proxy = f"{localurl}::{proxified}"
            return ((proxified, host, port, proxy, base_path))
        return ((f"http://localhost:{port}", host, port, None, "/"))