from .operation import *


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


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


def set_rule_cache(name: str, cs: ChangeSet) -> DbChangeSet:
    old = get_rule(name)

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

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

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

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


def set_rule(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, set_rule_cache(name, cs))


def inp_in_rule(section: list[str]) -> ChangeSet:
    cs = ChangeSet(g_update_prefix | {'type': 'rule', 'rules' : section})
    return cs


def inp_out_rule(name: str) -> list[str]:
    return get_rule(name)['rules']