from .operation import *


element_schema = {'type': 'str' , 'optional': True , 'readonly': False}


def get_energy_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'GLOBAL PRICE'   : element_schema,
             'GLOBAL PATTERN' : element_schema,
             'GLOBAL EFFIC'   : element_schema,
             'DEMAND CHARGE'  : element_schema }


def get_energy(name: str) -> dict[str, Any]:
    ts = read_all(name, f"select * from energy")
    d = {}
    for e in ts:
        d[e['key']] = str(e['value'])
    return d


def set_energy_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    raw_old = get_energy(name)

    old = {}
    new = {}

    new_dict = cs.operations[0]
    schema = get_energy_schema(name)
    for key in schema.keys():
        if key in new_dict:
            old[key] = str(raw_old[key])
            new[key] = str(new_dict[key])

    redo_cs = g_update_prefix | { 'type' : 'energy' }

    redo_sql = ''
    for key, value in new.items():
        if redo_sql != '':
            redo_sql += '\n'
        redo_sql += f"update energy set value = '{value}' where key = '{key}';"
        redo_cs |= { key: value }

    undo_cs = g_update_prefix | { 'type' : 'energy' }

    undo_sql = ''
    for key, value in old.items():
        if undo_sql != '':
            undo_sql += '\n'
        undo_sql += f"update energy set value = '{value}' where key = '{key}';"
        undo_cs |= { key: value }

    return SqlChangeSet(redo_sql, undo_sql, redo_cs, undo_cs)


def set_energy(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, set_energy_cache(name, cs))


def get_pump_energy_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'pump'    : {'type': 'str'   , 'optional': False , 'readonly': True },
             'price'   : {'type': 'float' , 'optional': True  , 'readonly': False},
             'pattern' : {'type': 'str'   , 'optional': True  , 'readonly': False},
             'effic'   : {'type': 'str'   , 'optional': True  , 'readonly': False} }


def get_pump_energy(name: str, pump: str) -> dict[str, Any]:
    d = {}
    d['pump'] = pump
    pe = try_read(name, f"select * from energy_pump_price where pump = '{pump}'")
    d['price'] = float(pe['price']) if pe != None else None
    pe = try_read(name, f"select * from energy_pump_pattern where pump = '{pump}'")
    d['pattern'] = str(pe['pattern']) if pe != None else None
    pe = try_read(name, f"select * from energy_pump_effic where pump = '{pump}'")
    d['effic'] = str(pe['effic']) if pe != None else None
    return d


class PumpEnergy(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'pump_energy'
        self.pump = str(input['pump'])
        self.price = float(input['price']) if 'price' in input and input['price'] != None else None
        self.pattern = str(input['pattern']) if 'pattern' in input and input['pattern'] != None else None
        self.effic = str(input['effic']) if 'effic' in input and input['effic'] != None else None

        self.f_type = f"'{self.type}'"
        self.f_pump = f"'{self.pump}'"
        self.f_price = self.price if self.price != None else 'null'
        self.f_pattern = f"'{self.pattern}'" if self.pattern != None else 'null'
        self.f_effic = f"'{self.effic}'" if self.effic != None else 'null'

    def as_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'pump': self.pump, 'price': self.price, 'pattern': self.pattern, 'effic': self.effic }


def set_pump_energy_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = PumpEnergy(get_pump_energy(name, cs.operations[0]['pump']))
    raw_new = get_pump_energy(name, cs.operations[0]['pump'])

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

    redo_sql = f"delete from energy_pump_price where pump = {new.f_pump};\ndelete from energy_pump_pattern where pump = {new.f_pump};\ndelete from energy_pump_effic where pump = {new.f_pump};"
    if new.price != None:
        redo_sql += f"\ninsert into energy_pump_price (pump, price) values ({new.f_pump}, {new.f_price});"
    if new.pattern != None:
        redo_sql += f"\ninsert into energy_pump_pattern (pump, pattern) values ({new.f_pump}, {new.f_pattern});"
    if new.effic != None:
        redo_sql += f"\ninsert into energy_pump_effic (pump, effic) values ({new.f_pump}, {new.f_effic});"

    undo_sql = f"delete from energy_pump_price where pump = {old.f_pump};\ndelete from energy_pump_pattern where pump = {old.f_pump};\ndelete from energy_pump_effic where pump = {old.f_pump};"
    if old.price != None:
        undo_sql += f"\ninsert into energy_pump_price (pump, price) values ({old.f_pump}, {old.f_price});"
    if old.pattern != None:
        undo_sql += f"\ninsert into energy_pump_pattern (pump, pattern) values ({old.f_pump}, {old.f_pattern});"
    if old.effic != None:
        undo_sql += f"\ninsert into energy_pump_effic (pump, effic) values ({old.f_pump}, {old.f_effic});"

    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_energy(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, set_pump_energy_cache(name, cs))


def inp_in_energy(section: list[str]) -> ChangeSet:
    cs = ChangeSet()

    for s in section:
        tokens = s.strip().split()

        if tokens[0].upper() == 'PUMP':
            pump = tokens[1]
            key = tokens[2].lower()
            value = tokens[3]
            if key == 'price':
                value = float(value)
            cs.append(g_update_prefix | { 'type' : 'pump_energy', 'pump' : pump, key: value })

        else:
            line = s.upper().strip()
            for key in get_energy_schema('').keys():
                if line.startswith(key):
                    value = line.removeprefix(key).strip()
                    cs.append(g_update_prefix | { 'type' : 'energy', key : value })

    return cs


def inp_out_energy(name: str) -> list[str]:
    lines = []

    objs = read_all(name, f"select * from energy")
    for obj in objs:
        key = obj['key']
        value = obj['value']
        lines.append(f'{key} {value}')

    objs = read_all(name, f"select * from energy_pump_price")
    for obj in objs:
        pump = obj['pump']
        value = obj['price']
        lines.append(f'PUMP {pump} PRICE {value}')

    objs = read_all(name, f"select * from energy_pump_pattern")
    for obj in objs:
        pump = obj['pump']
        value = obj['pattern']
        lines.append(f'PUMP {pump} PATTERN {value}')

    objs = read_all(name, f"select * from energy_pump_effic")
    for obj in objs:
        pump = obj['pump']
        value = obj['effic']
        lines.append(f'PUMP {pump} EFFIC {value}')

    return lines
