from .operation import *


def get_label_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'x'     : {'type': 'float' , 'optional': False , 'readonly': False},
             'y'     : {'type': 'float' , 'optional': False , 'readonly': False},
             'label' : {'type': 'str'   , 'optional': False , 'readonly': False},
             'node'  : {'type': 'str'   , 'optional': True  , 'readonly': False} }


def get_label(name: str, x: float, y: float) -> dict[str, Any]:
    d = {}
    d['x'] = x
    d['y'] = y
    l = try_read(name, f'select * from labels where x = {x} and y = {y}')
    if l == None:
        d['label'] = None
        d['node'] = None
    else:
        d['label'] = str(l['label'])
        d['node'] = str(l['node']) if l['node'] != None else None
    return d


class Label(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'label'
        self.x = float(input['x'])
        self.y = float(input['y'])
        self.label = str(input['label'])
        self.node = str(input['node']) if 'node' in input and input['node'] != None else None

        self.f_type = f"'{self.type}'"
        self.f_x = self.x
        self.f_y = self.y
        self.f_label = f"'{self.label}'"
        self.f_node = f"'{self.node}'" if self.node != None else 'null'

    def as_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'x': self.x, 'y': self.y, 'label': self.label, 'node': self.node }

    def as_xy_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'x': self.x, 'y': self.y }


def set_label_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = Label(get_label(name, cs.operations[0]['x'], cs.operations[0]['y']))
    raw_new = get_label(name, cs.operations[0]['x'], cs.operations[0]['y'])

    new_dict = cs.operations[0]
    schema = get_label_schema(name)
    for key, value in schema.items():
        if key in new_dict and not value['readonly']:
            raw_new[key] = new_dict[key]
    new = Label(raw_new)

    redo_sql = f"update labels set label = {new.f_label}, node = {new.f_node} where x = {new.f_x} and y = {new.f_y};"
    undo_sql = f"update labels set label = {old.f_label}, node = {old.f_node} where x = {old.f_x} and y = {old.f_y};"

    redo_cs = g_update_prefix | new.as_dict()
    undo_cs = g_update_prefix | old.as_dict()

    return SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def set_label(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, set_label_cache(name, cs))


def add_label_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    new = Label(cs.operations[0])

    redo_sql = f"insert into labels (x, y, label, node) values ({new.f_x}, {new.f_y}, {new.f_label}, {new.f_node});"
    undo_sql = f"delete from labels where x = {new.f_x} and y = {new.f_y};"

    redo_cs = g_add_prefix | new.as_dict()
    undo_cs = g_delete_prefix | new.as_xy_dict()

    return SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def add_label(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, add_label_cache(name, cs))


def delete_label_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = Label(get_label(name, cs.operations[0]['x'], cs.operations[0]['y']))

    redo_sql = f"delete from labels where x = {old.f_x} and y = {old.f_y};"
    undo_sql = f"insert into labels (x, y, label, node) values ({old.f_x}, {old.f_y}, {old.f_label}, {old.f_node});"

    redo_cs = g_delete_prefix | old.as_xy_dict()
    undo_cs = g_add_prefix | old.as_dict()

    return SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def delete_label(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, delete_label_cache(name, cs))
