from .operation 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 = read(name, f"select * from pumps where id = '{id}'")
    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


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_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    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 SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def set_pump(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, set_pump_cache(name, cs))


def add_pump_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    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 SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def add_pump(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, add_pump_cache(name, cs))


def delete_pump_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    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 SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def delete_pump(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, delete_pump_cache(name, cs))


class InpPump:
    def __init__(self, line: str) -> None:
        tokens = line.split()

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

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


def inp_in_pump(section: list[str]) -> ChangeSet:
    cs = ChangeSet()
    for s in section:
        # skip comment
        if s.startswith(';'):
            continue
        obj = InpPump(s)
        cs.append(g_add_prefix | {'type': 'pump', 'id': obj.id, 'node1': obj.node1, 'node2': obj.node2, 'power': obj.power, 'head': obj.head, 'speed': obj.speed, 'pattern': obj.pattern})
    return cs


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
