from .operation import *


def get_vertex_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'link'   : {'type': 'str'  , 'optional': False , 'readonly': True },
             'coords' : {'type': 'list' , 'optional': False , 'readonly': False, 
                           'element': { 'x'  : {'type': 'float' , 'optional': False , 'readonly': False }, 
                                        'y'  : {'type': 'float' , 'optional': False , 'readonly': False } }}}


def get_vertex(name: str, link: str) -> dict[str, Any]:
    cus = read_all(name, f"select * from vertices where link = '{link}' order by _order")
    cs = []
    for r in cus:
        cs.append({ 'x': float(r['x']), 'y': float(r['y']) })
    return { 'link': link, 'coords': cs }


def set_vertex_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    link = cs.operations[0]['link']

    old = get_vertex(name, link)
    new = { 'link': link, 'coords': [] }

    f_link = f"'{link}'"

    # TODO: transaction ?
    redo_sql = f"delete from vertices where link = {f_link};"
    for xy in cs.operations[0]['coords']:
        x, y = float(xy['x']), float(xy['y'])
        f_x, f_y = x, y
        redo_sql += f"\ninsert into vertices (link, x, y) values ({f_link}, {f_x}, {f_y});"
        new['coords'].append({ 'x': x, 'y': y })

    undo_sql = f"delete from vertices where link = {f_link};"
    for xy in old['coords']:
        f_x, f_y = xy['x'], xy['y']
        undo_sql += f"\ninsert into vertices (link, x, y) values ({f_link}, {f_x}, {f_y});"

    redo_cs = { 'type': 'vertex' } | new
    undo_cs = { 'type': 'vertex' } | old

    return SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def add_vertex_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    result = set_vertex_cache(name, cs)
    result.redo_cs |= g_add_prefix
    result.undo_cs |= g_delete_prefix
    return result


def delete_vertex_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    cs.operations[0]['coords'] = []
    result = set_vertex_cache(name, cs)
    result.redo_cs |= g_delete_prefix
    result.undo_cs |= g_add_prefix
    return result


def set_vertex(name: str, cs: ChangeSet) -> ChangeSet:
    result = set_vertex_cache(name, cs)
    result.redo_cs |= g_update_prefix
    result.undo_cs |= g_update_prefix
    return execute_command(name, result)


def add_vertex(name: str, cs: ChangeSet) -> ChangeSet:
    result = set_vertex_cache(name, cs)
    result.redo_cs |= g_add_prefix
    result.undo_cs |= g_delete_prefix
    return execute_command(name, result)


def delete_vertex(name: str, cs: ChangeSet) -> ChangeSet:
    cs.operations[0]['coords'] = []
    result = set_vertex_cache(name, cs)
    result.redo_cs |= g_delete_prefix
    result.undo_cs |= g_add_prefix
    return execute_command(name, result)


def inp_in_vertex(section: list[str]) -> ChangeSet:
    vertices: dict[str, list[dict[str, float]]] = {}

    for s in section:
        tokens = s.split()
        if tokens[0] not in vertices:
            vertices[tokens[0]] = []
        vertices[tokens[0]].append({'x': float(tokens[1]), 'y': float(tokens[2])})

    cs = ChangeSet()
    for link, coords in vertices.items():
        cs.append(g_add_prefix | {'type': 'vertex', 'link' : link, 'coords' : coords})
    return cs


def inp_out_vertex(name: str) -> list[str]:
    lines = []
    objs = read_all(name, f"select * from vertices order by _order")
    for obj in objs:
        link = obj['link']
        x = obj['x']
        y = obj['y']
        lines.append(f"{link} {x} {y}")
    return lines
