from .operation import *
from .s0_base import *


VALVES_TYPE_PRV = 'PRV'
VALVES_TYPE_PSV = 'PSV'
VALVES_TYPE_PBV = 'PBV'
VALVES_TYPE_FCV = 'FCV'
VALVES_TYPE_TCV = 'TCV'
VALVES_TYPE_GPV = 'GPV'


def get_valve_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'id'         : {'type': 'str'   , 'optional': False , 'readonly': True },
             'node1'      : {'type': 'str'   , 'optional': False , 'readonly': False},
             'node2'      : {'type': 'str'   , 'optional': False , 'readonly': False},
             'diameter'   : {'type': 'float' , 'optional': False , 'readonly': False},
             'v_type'     : {'type': 'str'   , 'optional': False , 'readonly': False},
             'setting'    : {'type': 'float' , 'optional': False , 'readonly': False},
             'minor_loss' : {'type': 'float' , 'optional': False , 'readonly': False} }


def get_valve(name: str, id: str) -> dict[str, Any]:
    p = read(name, f"select * from valves where id = '{id}'")
    d = {}
    d['id'] = str(p['id'])
    d['node1'] = str(p['node1'])
    d['node2'] = str(p['node2'])
    d['diameter'] = float(p['diameter'])
    d['v_type'] = str(p['type'])
    d['setting'] = float(p['setting'])
    d['minor_loss'] = float(p['minor_loss'])
    return d


class Valve(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'valve'
        self.id = str(input['id'])
        self.node1 = str(input['node1'])
        self.node2 = str(input['node2'])
        self.diameter = float(input['diameter'])
        self.v_type = str(input['v_type'])
        self.setting = float(input['setting'])
        self.minor_loss = float(input['minor_loss'])

        self.f_type = f"'{self.type}'"
        self.f_id = f"'{self.id}'"
        self.f_node1 = f"'{self.node1}'"
        self.f_node2 = f"'{self.node2}'"
        self.f_diameter = self.diameter
        self.f_v_type = f"'{self.v_type}'"
        self.f_setting = self.setting
        self.f_minor_loss = self.minor_loss

    def as_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'id': self.id, 'node1': self.node1, 'node2': self.node2, 'diameter': self.diameter, 'v_type': self.v_type, 'setting': self.setting, 'minor_loss': self.minor_loss }

    def as_id_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'id': self.id }


def set_valve(name: str, cs: ChangeSet) -> ChangeSet:
    old = Valve(get_valve(name, cs.operations[0]['id']))
    raw_new = get_valve(name, cs.operations[0]['id'])

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

    redo_sql = f"update valves set node1 = {new.f_node1}, node2 = {new.f_node2}, diameter = {new.f_diameter}, type = {new.f_v_type}, setting = {new.f_setting}, minor_loss = {new.f_minor_loss} where id = {new.f_id};"
    undo_sql = f"update valves set node1 = {old.f_node1}, node2 = {old.f_node2}, diameter = {old.f_diameter}, type = {old.f_v_type}, setting = {old.f_setting}, minor_loss = {old.f_minor_loss} where id = {old.f_id};"

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

    return execute_command(name, redo_sql, undo_sql, redo_cs, undo_cs)


def add_valve(name: str, cs: ChangeSet) -> ChangeSet:
    new = Valve(cs.operations[0])

    redo_sql = f"insert into _link (id, type) values ({new.f_id}, {new.f_type});"
    redo_sql += f"\ninsert into valves (id, node1, node2, diameter, type, setting, minor_loss) values ({new.f_id}, {new.f_node1}, {new.f_node2}, {new.f_diameter}, {new.f_v_type}, {new.f_setting}, {new.f_minor_loss});"

    undo_sql = f"delete from valves where id = {new.f_id};"
    undo_sql += f"\ndelete from _link where id = {new.f_id};"

    redo_cs = g_add_prefix | new.as_dict()
    undo_cs = g_delete_prefix | new.as_id_dict()

    return execute_command(name, redo_sql, undo_sql, redo_cs, undo_cs)


def delete_valve(name: str, cs: ChangeSet) -> ChangeSet:
    old = Valve(get_valve(name, cs.operations[0]['id']))

    redo_sql = f"delete from valves where id = {old.f_id};"
    redo_sql += f"\ndelete from _link where id = {old.f_id};"

    undo_sql = f"insert into _link (id, type) values ({old.f_id}, {old.f_type});"
    undo_sql += f"\ninsert into valves (id, node1, node2, diameter, type, setting, minor_loss) values ({old.f_id}, {old.f_node1}, {old.f_node2}, {old.f_diameter}, {old.f_v_type}, {old.f_setting}, {old.f_minor_loss});"

    redo_cs = g_delete_prefix | old.as_id_dict()
    undo_cs = g_add_prefix | old.as_dict()

    return execute_command(name, redo_sql, undo_sql, redo_cs, undo_cs)


'''
schema: dict[str, dict[str, Any]] = {}


def get_valve_schema(name: str) -> dict[str, dict[str, Any]]:
    return schema


def _query_valve(name: str, id: str) -> Row | None:
    return read(name, f"select * from valves where id = '{id}'")


def _get_valve_node1(name: str, id: str) -> str | None:
    row = _query_valve(name, id)
    return row['node1'] if row != None else None


def _get_valve_node2(name: str, id: str) -> str | None:
    row = _query_valve(name, id)
    return row['node2'] if row != None else None


def add_valve(name: str, id: str, node1: str, node2: str, diameter: float = 0, type: str = VALVES_TYPE_PRV, setting: float = 0, minor_loss: float = 0) -> ChangeSet:
    if is_valve(name, id):
        return ChangeSet()
    if not is_node(name, node1):
        return ChangeSet()
    if not is_node(name, node2):
        return ChangeSet()
    if node1 == node2:
        return ChangeSet()
    if type != VALVES_TYPE_PRV and type != VALVES_TYPE_PSV and type != VALVES_TYPE_PBV and type != VALVES_TYPE_FCV and type != VALVES_TYPE_TCV and type != VALVES_TYPE_GPV:
        return ChangeSet()

    sql = f"insert into _link (id, type) values ('{id}', '{VALVE}');"
    sql += f"\ninsert into valves (id, node1, node2, diameter, type, setting, minor_loss) values ('{id}', '{node1}', '{node2}', {diameter}, '{type}', {setting}, {minor_loss});"

    undo = f"delete from valves where id = ''{id}'';"
    undo += f"\ndelete from _link where id = ''{id}'';"

    write(name, sql)
    add_operation(name, sql.replace("'", "''"), undo, 'add_valve', API_ADD, VALVE, id)
    return get_current_change_set(name)


def get_valve(name: str, id: str) -> dict[str, Any] | None:
    row = _query_valve(name, id)
    if row == None:
        return None

    ps: dict[str, str] = {}
    ps['id'] = id
    ps['node1'] = row['node1']
    ps['node2'] = row['node2']
    ps['diameter'] = float(row['diameter'])
    ps['type'] = row['type']
    ps['setting'] = float(row['setting'])
    ps['minor_loss'] = float(row['minor_loss'])
    return ps


def set_valve(name: str, id: str, properties: dict[str, Any]) -> ChangeSet:
    if not is_valve(name, id):
        return ChangeSet()
    if 'node1' in properties:
        if not is_node(name, properties['node1']) or _get_valve_node2(name, id) == properties['node1']:
            return ChangeSet()
    if 'node2' in properties:
        if not is_node(name, properties['node2']) or _get_valve_node1(name, id) == properties['node2']:
            return ChangeSet()
    if 'node1' in properties and 'node2' in properties:
        if properties['node1'] == properties['node2']:
            return ChangeSet()
    if 'type' in properties:
        t = properties['type']
        if t != VALVES_TYPE_PRV and t != VALVES_TYPE_PSV and t != VALVES_TYPE_PBV and t != VALVES_TYPE_FCV and t != VALVES_TYPE_TCV and t != VALVES_TYPE_GPV:
            return ChangeSet()

    old = Serialize(get_valve(name, id), schema).to_storage()

    new = get_valve(name, id)
    ps: list[str] = []
    for key in properties:
        if key in schema and schema[key]['readonly'] == False:
            new[key] = properties[key]
            ps.append(key)
    new = Serialize(new, schema).to_execution()

    sql = f"update valves set node1 = {new['node1']}, node2 = {new['node2']}, \
        diameter = {new['diameter']}, type = {new['type']}, setting = {new['setting']}, minor_loss = {new['minor_loss']} where id = '{id}';"
    undo = f"update valves set node1 = {old['node1']}, node2 = {old['node2']}, \
        diameter = {old['diameter']}, type = {old['type']}, setting = {old['setting']}, minor_loss = {old['minor_loss']} where id = ''{id}'';"

    write(name, sql)
    add_operation(name, sql.replace("'", "''"), undo, 'set_valve', API_UPDATE, VALVE, id, ps)
    return get_current_change_set(name)


def delete_valve(name: str, id: str) -> ChangeSet:
    row = get_valve(name, id)
    if row == None:
        return ChangeSet()

    old = Serialize(get_valve(name, id), schema).to_storage()

    sql = f"delete from valves where id = '{id}';"
    sql += f"\ndelete from _link where id = '{id}';"

    undo = f"insert into _link (id, type) values (''{id}'', ''{VALVE}'');"
    undo += f"\ninsert into valves (id, node1, node2, diameter, type, setting, minor_loss) \
        values (''{id}'', {old['node1']}, {old['node2']}, {old['diameter']}, {old['type']}, {old['setting']}, {old['minor_loss']});"

    write(name, sql)
    add_operation(name, sql.replace("'", "''"), undo, 'delete_valve', API_DELETE, VALVE, id)
    return get_current_change_set(name)
'''