from .database import *
from .s0_base import *


def get_pump_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},
             'power'   : {'type': 'float' , 'optional': True  , 'readonly': False},
             'head'    : {'type': 'str'   , 'optional': True  , 'readonly': False},
             'speed'   : {'type': 'float' , 'optional': True  , 'readonly': False},
             'pattern' : {'type': 'str'   , 'optional': True  , 'readonly': False} }


def get_pump(name: str, id: str) -> dict[str, Any]:
    p = try_read(name, f"select * from pumps where id = '{id}'")
    if p == None:
        return {}
    d = {}
    d['id'] = str(p['id'])
    d['node1'] = str(p['node1'])
    d['node2'] = str(p['node2'])
    d['power'] = float(p['power']) if p['power'] != None else None
    d['head'] = str(p['head']) if p['head'] != None else None
    d['speed'] = float(p['speed']) if p['speed'] != None else None
    d['pattern'] = str(p['pattern']) if p['pattern'] != None else None
    return d

# DingZQ, 2025-03-29
def get_all_pumps(name: str) -> list[dict[str, Any]]:
    rows = read_all(name, f"select * from pumps")
    if rows == None:
        return []

    result = []
    for row in rows:
        d = {}
        d['id'] = str(row['id'])
        d['node1'] = str(row['node1'])
        d['node2'] = str(row['node2'])
        d['power'] = float(row['power']) if row['power'] != None else None
        d['head'] = str(row['head']) if row['head'] != None else None
        d['speed'] = float(row['speed']) if row['speed'] != None else None
        d['pattern'] = str(row['pattern']) if row['pattern'] != None else None
        result.append(d)

    return result



class Pump(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'pump'
        self.id = str(input['id'])
        self.node1 = str(input['node1'])
        self.node2 = str(input['node2'])
        self.power = float(input['power']) if 'power' in input and input['power'] != None else None
        self.head = str(input['head']) if 'head' in input and input['head'] != None else None
        self.speed = float(input['speed']) if 'speed' in input and input['speed'] != None else None
        self.pattern = str(input['pattern']) if 'pattern' in input and input['pattern'] != None else None

        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_power = self.power if self.power != None else 'null'
        self.f_head = f"'{self.head}'" if self.head != None else 'null'
        self.f_speed = self.speed if self.speed != None else 'null'
        self.f_pattern = f"'{self.pattern}'" if self.pattern != None else 'null'

    def as_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'id': self.id, 'node1': self.node1, 'node2': self.node2, 'power': self.power, 'head': self.head, 'speed': self.speed, 'pattern': self.pattern }

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


def _set_pump(name: str, cs: ChangeSet) -> DbChangeSet:
    old = Pump(get_pump(name, cs.operations[0]['id']))
    raw_new = get_pump(name, cs.operations[0]['id'])

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

    redo_sql = f"update pumps set node1 = {new.f_node1}, node2 = {new.f_node2}, power = {new.f_power}, head = {new.f_head}, speed = {new.f_speed}, pattern = {new.f_pattern} where id = {new.f_id};"
    undo_sql = f"update pumps set node1 = {old.f_node1}, node2 = {old.f_node2}, power = {old.f_power}, head = {old.f_head}, speed = {old.f_speed}, pattern = {old.f_pattern} where id = {old.f_id};"

    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_pump(name: str, cs: ChangeSet) -> ChangeSet:
    if 'id' not in cs.operations[0]:
        return ChangeSet()
    if get_pump(name, cs.operations[0]['id']) == {}:
        return ChangeSet()
    return execute_command(name, _set_pump(name, cs))


def _add_pump(name: str, cs: ChangeSet) -> DbChangeSet:
    new = Pump(cs.operations[0])

    redo_sql = f"insert into _link (id, type) values ({new.f_id}, {new.f_type});"
    redo_sql += f"\ninsert into pumps (id, node1, node2, power, head, speed, pattern) values ({new.f_id}, {new.f_node1}, {new.f_node2}, {new.f_power}, {new.f_head}, {new.f_speed}, {new.f_pattern});"

    undo_sql = f"delete from pumps 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 DbChangeSet(redo_sql, undo_sql, [redo_cs], [undo_cs])


def add_pump(name: str, cs: ChangeSet) -> ChangeSet:
    if 'id' not in cs.operations[0]:
        return ChangeSet()
    if get_pump(name, cs.operations[0]['id']) != {}:
        return ChangeSet()
    return execute_command(name, _add_pump(name, cs))


def _delete_pump(name: str, cs: ChangeSet) -> DbChangeSet:
    old = Pump(get_pump(name, cs.operations[0]['id']))

    redo_sql = f"delete from pumps 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 pumps (id, node1, node2, power, head, speed, pattern) values ({old.f_id}, {old.f_node1}, {old.f_node2}, {old.f_power}, {old.f_head}, {old.f_speed}, {old.f_pattern});"

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

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


def delete_pump(name: str, cs: ChangeSet) -> ChangeSet:
    if 'id' not in cs.operations[0]:
        return ChangeSet()
    if get_pump(name, cs.operations[0]['id']) == {}:
        return ChangeSet()
    return execute_command(name, _delete_pump(name, cs))


#--------------------------------------------------------------
# [EPA2][EPA3][IN][OUT]
#   id  node1  node2  KEYWORD value {KEYWORD value ...} ;desc
#   where KEYWORD = [POWER,HEAD,PATTERN,SPEED]
#--------------------------------------------------------------


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

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

    id = str(tokens[0])
    node1 = str(tokens[1])
    node2 = str(tokens[2])
    props = {}
    for i in range(3, num_without_desc, 2):
        props |= { tokens[i].lower(): tokens[i + 1] }
    power = float(props['power']) if 'power' in props else None
    power = power if power != None else 'null'
    head = str(props['head']) if 'head' in props else None
    head = f"'{head}'" if head != None else 'null'
    speed = float(props['speed']) if 'speed' in props else None
    speed = speed if speed != None else 'null'
    pattern = str(props['pattern']) if 'pattern' in props else None
    pattern = f"'{pattern}'" if pattern != None else 'null'
    desc = str(tokens[-1]) if has_desc else None

    return str(f"insert into _link (id, type) values ('{id}', 'pump');insert into pumps (id, node1, node2, power, head, speed, pattern) values ('{id}', '{node1}', '{node2}', {power}, {head}, {speed}, {pattern});")


def inp_out_pump(name: str) -> list[str]:
    lines = []
    objs = read_all(name, 'select * from pumps')
    for obj in objs:
        id = obj['id']
        node1 = obj['node1']
        node2 = obj['node2']
        power = f"POWER {obj['power']}" if obj['power'] != None else ''
        head = f"HEAD {obj['head']}" if obj['head'] != None else ''
        speed = f"SPEED {obj['speed']}" if obj['speed'] != None else ''
        pattern = f"PATTERN {obj['pattern']}" if obj['pattern'] != None else ''
        desc = ';'
        lines.append(f'{id} {node1} {node2} {power} {head} {speed} {pattern} {desc}')
    return lines


'''def delete_pump_by_node(name: str, node: str) -> ChangeSet:
    cs = ChangeSet()

    rows = read_all(name, f"select id from pumps where node1 = '{node}' or node2 = '{node}'")
    for row in rows:
        cs.append(g_delete_prefix | {'type': 'pump', 'id': row['id']})

    return cs'''


def unset_pump_by_curve(name: str, curve: str) -> ChangeSet:
    cs = ChangeSet()

    rows = read_all(name, f"select * from pumps where head = '{curve}'")
    for row in rows:
        if row['power'] != None:
            cs.append(g_update_prefix | {'type': 'pump', 'id': row['id'], 'head': None})
        else: # workaround to prevent pump deletion... and I don't want to remove constraint...
            cs.append(g_update_prefix | {'type': 'pump', 'id': row['id'], 'head': None, 'power': 0.0})

    return cs


def unset_pump_by_pattern(name: str, pattern: str) -> ChangeSet:
    cs = ChangeSet()

    rows = read_all(name, f"select id from pumps where pattern = '{pattern}'")
    for row in rows:
        cs.append(g_update_prefix | {'type': 'pump', 'id': row['id'], 'pattern': None})

    return cs
