from datetime import datetime

from . import glob
from helpers.uuid import generate as generate_uuid

class Display:
    def __init__(self, uuid):
        if uuid in glob.displays.keys():
            raise Exception("Display with this UUID already exists!")
        glob.displays[uuid] = self

        self.uuid = uuid
        self.connections = set() # maybe set()?
        self.windows = [] # maybe set()?

        self.title = None
        self.start_time = int( datetime.now().timestamp() )
        self.kill_time = self.start_time + glob.config["display"]["timeout"]
    
    def attach(self, sid):
        self.connections.add(sid)
        glob.connections[sid].add(self)

        self.kill_time = None

    def detach(self, sid):
        self.connections.remove(sid)
        glob.connections[sid].remove(self)

        if len(self.connections) == 0:
            self.kill_time = int( datetime.now().timestamp() ) + glob.config["display"]["timeout"]

    def serialize(self):
        return {
            "uuid": self.uuid,
            "connections": len(self.connections),
            "title": self.title,
            "start_time": self.start_time,
            "kill_time": self.kill_time
        }

    def __str__(self):
        return self.uuid

    @staticmethod
    def generate():
        while True:
            uuid = generate_uuid()
            if uuid not in glob.displays.keys():
                break
        return Display(uuid)

class Window:
    def __init__(self, uuid,
            title = "__unnamed__",
            grid_column = (0, 0),
            grid_row = (0, 0)):
        if uuid in glob.windows.keys():
            raise Exception("Window with this UUID already exists!")
        glob.windows[uuid] = self

        self.uuid = uuid
        self.title = title

        self.grid_column = grid_column
        self.grid_row = grid_row

        self.parents = set()

        self.tabs = [] # Maybe set()?

    def set_title(self, title):
        self.title = title
        # TODO: PUSH TITLE CHANGE
    
    def set_grid_column(self, grid_column):
        self.grid_column = grid_column
        # TODO: PUSH CHANGE
    
    def set_grid_row(self, grid_row):
        self.grid_row = grid_row
        # TODO: PUSH CHANGE
    
    def add_tab(self, tab):
        self.tabs.append(tab)
        # TODO: PUSH CHANGE
    
    def remove_tab(self, tab):
        self.tabs.remove(tab)
        # TODO: CHECK REF COUNT AND FREE IF 0
        # TODO: PUSH CHANGE

class Tab:
    def __init__(self, uuid,
            title = "__unnamed__"):
        if uuid in glob.tabs.keys():
            raise Exception("Tab with this UUID already exists!")
        glob.tabs[uuid] = self
            
        self.uuid = uuid
        self.content = ""

    def clear(self):
        self.content = ""
        # TODO: PUSH CHANGE

    def write_ln(self, data):
        self.write(data + "\n")

    def write(self, data):
        self.content += data
        # TODO: PUSH CHANGE

    def write_index(self, data, cursor): # Maybe also send snippet of before and after incase of multiedit?
        self.content = self.content[:cursor] + data + self.content[cursor:]
        # TODO: PUSH CHANGE