from .operation 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_cache(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_cache(name, cs))


def inp_in_control(section: list[str]) -> ChangeSet:
    cs = ChangeSet(g_update_prefix | {'type': 'control', 'controls' : section})
    return cs


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