from .operation import *


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


def get_global_energy(name: str) -> dict[str, Any]:
    ge = read(name, f"select * from energy_global")
    d = {}
    d['price'] = float(ge['price'])
    d['pattern'] = str(ge['pattern']) if ge['pattern'] != None else None
    d['effic'] = float(ge['effic'])
    d['demand_charge'] = float(ge['demand_charge'])
    return d


class GlobalEnergy(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'global_energy'
        self.price = float(input['price']) if 'price' in input and input['price'] != None else 0.0
        self.pattern = str(input['pattern']) if 'pattern' in input and input['pattern'] != None else None
        self.effic = float(input['effic']) if 'effic' in input and input['effic'] != None else 75
        self.demand_charge = float(input['demand_charge']) if 'demand_charge' in input and input['demand_charge'] != None else 0.0

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

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


def set_global_energy_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = GlobalEnergy(get_global_energy(name))
    raw_new = get_global_energy(name)

    new_dict = cs.operations[0]
    schema = get_global_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 = GlobalEnergy(raw_new)

    redo_sql = f"update energy_global set price = {new.f_price}, pattern = {new.f_pattern}, effic = {new.f_effic}, demand_charge = {new.f_demand_charge} where _no = 0;"
    undo_sql = f"update energy_global set price = {old.f_price}, pattern = {old.f_pattern}, effic = {old.f_effic}, demand_charge = {old.f_demand_charge} where _no = 0;"

    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_global_energy(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, set_global_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_pump = f"'{self.pump}'"
        self.f_type = f"'{self.type}'"
        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))
