from .database import *
from .s32_region_util import from_postgis_polygon, to_postgis_polygon

def get_region_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'id'        : {'type': 'str'        , 'optional': False , 'readonly': True },
             'boundary'  : {'type': 'tuple_list' , 'optional': False , 'readonly': False} }


def get_region(name: str, id: str) -> dict[str, Any]:
    r = try_read(name, f"select id, st_astext(boundary) as boundary_geom from region where id = '{id}'")
    if r == None:
        return {}
    d = {}
    d['id'] = str(r['id'])
    d['boundary'] = from_postgis_polygon(str(r['boundary_geom']))
    return d


def _set_region(name: str, cs: ChangeSet) -> DbChangeSet:
    id = cs.operations[0]['id']
    new = cs.operations[0]['boundary']
    old = get_region(name, id)['boundary']

    redo_sql = f"update region set boundary = st_geomfromtext('{to_postgis_polygon(new)}') where id = '{id}';"
    undo_sql = f"update region set boundary = st_geomfromtext('{to_postgis_polygon(old)}') where id = '{id}';"
    redo_cs = g_update_prefix | { 'type': 'region', 'id': id, 'boundary': new }
    undo_cs = g_update_prefix | { 'type': 'region', 'id': id, 'boundary': old }

    return DbChangeSet(redo_sql, undo_sql, [redo_cs], [undo_cs])


def set_region(name: str, cs: ChangeSet) -> ChangeSet:
    if 'id' not in cs.operations[0] or 'boundary' not in cs.operations[0]:
        return ChangeSet()
    b = cs.operations[0]['boundary']
    if len(b) < 4 or b[0] != b[-1]:
        return ChangeSet()
    if get_region(name, cs.operations[0]['id']) == {}:
        return ChangeSet()
    return execute_command(name, _set_region(name, cs))


def _add_region(name: str, cs: ChangeSet) -> DbChangeSet:
    id = cs.operations[0]['id']
    new = cs.operations[0]['boundary']

    redo_sql = f"insert into region (id, boundary) values ('{id}', '{to_postgis_polygon(new)}');"
    undo_sql = f"delete from region where id = '{id}';"
    redo_cs = g_add_prefix | { 'type': 'region', 'id': id, 'boundary': new }
    undo_cs = g_delete_prefix | { 'type': 'region', 'id': id }

    return DbChangeSet(redo_sql, undo_sql, [redo_cs], [undo_cs])


def add_region(name: str, cs: ChangeSet) -> ChangeSet:
    if 'id' not in cs.operations[0] or 'boundary' not in cs.operations[0]:
        return ChangeSet()
    b = cs.operations[0]['boundary']
    if len(b) < 4 or b[0] != b[-1]:
        return ChangeSet()
    if get_region(name, cs.operations[0]['id']) != {}:
        return ChangeSet()
    return execute_command(name, _add_region(name, cs))


def _delete_region(name: str, cs: ChangeSet) -> DbChangeSet:
    id = cs.operations[0]['id']
    old = get_region(name, id)['boundary']

    redo_sql = f"delete from region where id = '{id}';"
    undo_sql = f"insert into region (id, boundary) values ('{id}', '{to_postgis_polygon(old)}');"
    redo_cs = g_delete_prefix | { 'type': 'region', 'id': id }
    undo_cs = g_add_prefix | { 'type': 'region', 'id': id, 'boundary': old }

    return DbChangeSet(redo_sql, undo_sql, [redo_cs], [undo_cs])


def delete_region(name: str, cs: ChangeSet) -> ChangeSet:
    if 'id' not in cs.operations[0]:
        return ChangeSet()
    if get_region(name, cs.operations[0]['id']) == {}:
        return ChangeSet()
    return execute_command(name, _delete_region(name, cs))

def inp_in_region(line: str) -> str:
    tokens = line.split()
    return str(f"insert into _region (id, type) values ('{tokens[0]}', '{tokens[1]}');")

def inp_in_bound(line: str) -> str:
    tokens = line.split()
    return tokens[0]

def inp_in_regionnodes(line: str)->str:
    tokens = line.split()
    return tokens[0]