import json

from flask import request
from flask_socketio import emit

from objects.display import Display, Window, Tab
from objects import glob

from helpers import uuid, connection

@glob.websocket.on_error_default  # handles all namespaces without an explicit error handler
def default_error_handler(e):
    print("ERR:", e)
    return 500

@glob.websocket.on("connect")
def ws_connect():
    connection.connect(request.sid)
    return "hi"

@glob.websocket.on("disconnect")
def ws_disconnect():
    connection.disconnect(request.sid)

@glob.websocket.on("display")
def ws_display(data):
    def handle_list(_):
        return [ item.serialize() for item in glob.displays.values() ]
    
    def handle_new(_):
        display = Display.generate()
        return display.serialize()
    
    def handle_connect(data):
        uuid = data["uuid"]
        if uuid not in glob.displays.keys():
            raise Exception("Display not found")

        glob.displays[uuid].attach(request.sid)
        #print(dir(request))
        #print(request.sid)
        #print("TODO")

    switch = {
        "list": handle_list,
        "new": handle_new,
        "connect": handle_connect
    }
    return switch.get(data["action"])(data)