from .operation import *


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


def get_control(name: str) -> dict[str, Any]:
    e = read(name, f"select * from controls")
    return { 'control': e['control'] }


def set_control_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = get_control(name)

    redo_sql = f"update controls set control = '{cs.operations[0]['control']}' where control = '{old['control']}';"
    undo_sql = f"update controls set control = '{old['control']}' where control = '{cs.operations[0]['control']}';"

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

    return SqlChangeSet(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))


class InpControl:
    def __init__(self, section) -> None:
        self.control = '\n'.join(section)


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


def inp_out_control(name: str) -> list[str]:
    obj = str(get_control(name)['control'])
    return obj.split('\n')
