from .database 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(name: str, cs: ChangeSet) -> DbChangeSet:
    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 DbChangeSet(redo_sql, undo_sql, [redo_cs], [undo_cs])


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


def _add_vertex(name: str, cs: ChangeSet) -> DbChangeSet:
    result = _set_vertex(name, cs)
    result.redo_cs[0] |= g_add_prefix
    result.undo_cs[0] |= g_delete_prefix
    return result


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


def add_vertex(name: str, cs: ChangeSet) -> ChangeSet:
    result = _add_vertex(name, cs)
    return execute_command(name, result)


def delete_vertex(name: str, cs: ChangeSet) -> ChangeSet:
    result = _delete_vertex(name, cs)
    return execute_command(name, result)


def get_all_vertex_links(name: str) -> list[str]:
    result : list[str] = []
    rows = read_all(name, 'select link from vertices order by link')
    for row in rows:
        result.append(str(row['link']))
    return result


def get_all_vertices(name: str) -> list[dict[str, Any]]:
    return read_all(name, 'select * from vertices order by link')


#--------------------------------------------------------------
# [EPA2][IN][OUT]
#   id  x  y
# [EPA3][NOT SUPPORT]
#--------------------------------------------------------------


def inp_in_vertex(line: str) -> str:
    tokens = line.split()
    link = tokens[0]
    x = float(tokens[1])
    y = float(tokens[2])
    return str(f"insert into vertices (link, x, y) values ('{link}', {x}, {y});")


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


def delete_vertex_by_link(name: str, link: str) -> ChangeSet:
    row = try_read(name, f"select * from vertices where link = '{link}'")
    if row == None:
        return ChangeSet()
    return ChangeSet(g_delete_prefix | {'type': 'vertex', 'link' : link})
