from .database import *


def get_control_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'controls' : {'type': 'str_list' , 'optional': False , 'readonly': False} }


def get_control(name: str) -> dict[str, Any]:
    cs = read_all(name, f"select * from controls")
    ds = []
    for c in cs:
        ds.append(c['line'])
    return { 'controls': ds }


def _set_control(name: str, cs: ChangeSet) -> DbChangeSet:
    old = get_control(name)

    redo_sql = 'delete from controls;'
    for line in cs.operations[0]['controls']:
        redo_sql += f"\ninsert into controls (line) values ('{line}');"

    undo_sql = 'delete from controls;'
    for line in old['controls']:
        undo_sql += f"\ninsert into controls (line) values ('{line}');"

    redo_cs = g_update_prefix | { 'type': 'control', 'controls': cs.operations[0]['controls'] }
    undo_cs = g_update_prefix | { 'type': 'control', 'controls': old['controls'] }

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


def set_control(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, _set_control(name, cs))


#--------------------------------------------------------------
# [EPA2][EPA3]
#   LINK  linkID  setting IF NODE      nodeID {BELOW/ABOVE}  level
#   LINK  linkID  setting AT TIME      value  (units)
#   LINK  linkID  setting AT CLOCKTIME value  (units)
#    (0)   (1)      (2)   (3) (4)       (5)     (6)          (7)
# todo...
#--------------------------------------------------------------


def inp_in_control(line: str) -> str:
    return str(f"insert into controls (line) values ('{line}');")


def inp_out_control(name: str) -> list[str]:
    return get_control(name)['controls']
