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


#--------------------------------------------------------------
# [EPA2][EPA3]
#   TODO...
#--------------------------------------------------------------


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


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