from .database import *


def get_quality_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'node'    : {'type': 'str'   , 'optional': False , 'readonly': True },
             'quality' : {'type': 'float' , 'optional': True ,  'readonly': False} }


def get_quality(name: str, node: str) -> dict[str, Any]:
    e = try_read(name, f"select * from quality where node = '{node}'")
    if e == None:
        return { 'node': node, 'quality': None }
    d = {}
    d['node'] = str(e['node'])
    d['quality'] = float(e['quality']) if e['quality'] != None else None
    return d


class Quality(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'quality'
        self.node = str(input['node'])
        self.quality = float(input['quality']) if 'quality' in input and input['quality'] != None else None

        self.f_type = f"'{self.type}'"
        self.f_node = f"'{self.node}'"
        self.f_quality = self.quality if self.quality != None else 'null'

    def as_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'node': self.node, 'quality': self.quality }


def _set_quality(name: str, cs: ChangeSet) -> DbChangeSet:
    old = Quality(get_quality(name, cs.operations[0]['node']))
    raw_new = get_quality(name, cs.operations[0]['node'])

    new_dict = cs.operations[0]
    schema = get_quality_schema(name)
    for key, value in schema.items():
        if key in new_dict and not value['readonly']:
            raw_new[key] = new_dict[key]
    new = Quality(raw_new)

    redo_sql = f"delete from quality where node = {new.f_node};"
    if new.quality != None:
        redo_sql += f"\ninsert into quality (node, quality) values ({new.f_node}, {new.f_quality});"

    undo_sql = f"delete from quality where node = {old.f_node};"
    if old.quality != None:
        undo_sql += f"\ninsert into quality (node, quality) values ({old.f_node}, {old.f_quality});"

    redo_cs = g_update_prefix | new.as_dict()
    undo_cs = g_update_prefix | old.as_dict()

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


def set_quality(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, _set_quality(name, cs))


#--------------------------------------------------------------
# [EPA2][EPA3][IN][OUT]
#   node   initqual
#--------------------------------------------------------------


def inp_in_quality(line: str) -> str:
    tokens = line.split()

    num = len(tokens)
    has_desc = tokens[-1].startswith(';')
    num_without_desc = (num - 1) if has_desc else num

    node = str(tokens[0])
    quality = float(tokens[1])

    return str(f"insert into quality (node, quality) values ('{node}', {quality});")


def inp_out_quality(name: str) -> list[str]:
    lines = []
    objs = read_all(name, 'select * from quality')
    for obj in objs:
        node = obj['node']
        quality = obj['quality']
        lines.append(f'{node} {quality}')
    return lines


def delete_quality_by_node(name: str, node: str) -> ChangeSet:
    row = try_read(name, f"select * from quality where node = '{node}'")
    if row == None:
        return ChangeSet()
    return ChangeSet(g_update_prefix | {'type' : 'quality', 'node': node, 'quality': None})
