from .operation import *
from .s0_base import *

MIXING_MODEL_MIXED = 'MIXED'
MIXING_MODEL_2COMP = '2COMP'
MIXING_MODEL_FIFO = 'FIFO'
MIXING_MODEL_LIFO = 'LIFO'

def get_mixing_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'tank'  : {'type': 'str'   , 'optional': False , 'readonly': True },
             'model' : {'type': 'str'   , 'optional': False , 'readonly': False},
             'value' : {'type': 'float' , 'optional': True ,  'readonly': False} }


def get_mixing(name: str, tank: str) -> dict[str, Any]:
    m = read(name, f"select * from mixing where tank = '{tank}'")
    d = {}
    d['tank'] = str(m['tank'])
    d['model'] = str(m['model'])
    d['value'] = float(m['value']) if m['value'] != None else None
    return d


class Mixing(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'mixing'
        self.tank = str(input['tank'])
        self.model = str(input['model'])
        self.value = float(input['value']) if 'value' in input and input['value'] != None else None

        self.f_type = f"'{self.type}'"
        self.f_tank = f"'{self.tank}'"
        self.f_model = f"'{self.model}'"
        self.f_value = self.value if self.value != None else 'null'

    def as_dict(self) -> dict[str, Any]:
        return { 'type': self.type, 'tank': self.tank, 'model': self.model, 'value': self.value }

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


def set_mixing_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = Mixing(get_mixing(name, cs.operations[0]['tank']))
    raw_new = get_mixing(name, cs.operations[0]['tank'])

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

    redo_sql = f"update mixing set model = {new.f_model}, value = {new.f_value} where tank = {new.f_tank};"
    undo_sql = f"update mixing set model = {old.f_model}, value = {old.f_value} where tank = {old.f_tank};"

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


def add_mixing_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    new = Mixing(cs.operations[0])

    redo_sql = f"insert into mixing (tank, model, value) values ({new.f_tank}, {new.f_model}, {new.f_value});"
    undo_sql = f"delete from mixing where tank = {new.f_tank};"

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


def delete_mixing_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = Mixing(get_mixing(name, cs.operations[0]['tank']))

    redo_sql = f"delete from mixing where tank = {old.f_tank};"
    undo_sql = f"insert into mixing (tank, model, value) values ({old.f_tank}, {old.f_model}, {old.f_value});"

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


class InpMixing:
    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.tank = str(tokens[0])
        self.model = str(tokens[1])
        self.value = float(tokens[3]) if num_without_desc >= 4 else None


def inp_in_mixing(section: list[str]) -> ChangeSet:
    cs = ChangeSet()
    for s in section:
        # skip comment
        if s.startswith(';'):
            continue
        obj = InpMixing(s)
        cs.append(g_add_prefix | {'type': 'mixing', 'tank': obj.tank, 'model': obj.model, 'value': obj.value})
    return cs


def inp_out_mixing(name: str) -> list[str]:
    lines = []
    objs = read_all(name, 'select * from mixing')
    for obj in objs:
        tank = obj['tank']
        model = obj['model']
        value = obj['value'] if obj['value'] != None else ''
        lines.append(f'{tank} {model} {value}')
    return lines
