from .operation import *


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


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


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

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

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

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


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


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


def inp_out_rule(name: str) -> list[str]:
    obj = str(get_rule(name)['rule'])
    return obj.split('\n')
