from .operation import *
from .s0_base import *
from .s24_coordinates import *


def get_reservoir_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'id'      : {'type': 'str'      , 'optional': False , 'readonly': True },
             'x'       : {'type': 'float'    , 'optional': False , 'readonly': False},
             'y'       : {'type': 'float'    , 'optional': False , 'readonly': False},
             'head'    : {'type': 'float'    , 'optional': False , 'readonly': False},
             'pattern' : {'type': 'str'      , 'optional': True  , 'readonly': False},
             'links'   : {'type': 'str_list' , 'optional': False , 'readonly': True } }


def get_reservoir(name: str, id: str) -> dict[str, Any]:
    r = read(name, f"select * from reservoirs where id = '{id}'")
    xy = get_node_coord(name, id)
    d = {}
    d['id'] = str(r['id'])
    d['x'] = float(xy['x'])
    d['y'] = float(xy['y'])
    d['head'] = float(r['head'])
    d['pattern'] = str(r['pattern']) if r['pattern'] != None else None
    d['links'] = get_node_links(name, id)
    return d


class Reservoir(object):
    def __init__(self, input: dict[str, Any]) -> None:
        self.type = 'reservoir'
        self.id = str(input['id'])
        self.x = float(input['x'])
        self.y = float(input['y'])
        self.head = float(input['head'])
        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_coord = f"'({self.x}, {self.y})'"
        self.f_head = self.head
        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, 'x': self.x, 'y': self.y, 'head': self.head, 'pattern': self.pattern }

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


def set_reservoir_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = Reservoir(get_reservoir(name, cs.operations[0]['id']))
    raw_new = get_reservoir(name, cs.operations[0]['id'])

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

    redo_sql = f"update reservoirs set head = {new.f_head}, pattern = {new.f_pattern} where id = {new.f_id};"
    redo_sql += f"\nupdate coordinates set coord = {new.f_coord} where node = {new.f_id};"

    undo_sql = f"update coordinates set coord = {old.f_coord} where node = {old.f_id};"
    undo_sql += f"\nupdate reservoirs set head = {old.f_head}, 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_reservoir(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, set_reservoir_cache(name, cs))


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

    redo_sql = f"insert into _node (id, type) values ({new.f_id}, {new.f_type});"
    redo_sql += f"\ninsert into reservoirs (id, head, pattern) values ({new.f_id}, {new.f_head}, {new.f_pattern});"
    redo_sql += f"\ninsert into coordinates (node, coord) values ({new.f_id}, {new.f_coord});"

    undo_sql = f"delete from coordinates where node = {new.f_id};"
    undo_sql += f"\ndelete from reservoirs where id = {new.f_id};"
    undo_sql += f"\ndelete from _node 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_reservoir(name: str, cs: ChangeSet) -> ChangeSet:
    return execute_command(name, add_reservoir_cache(name, cs))


def delete_reservoir_cache(name: str, cs: ChangeSet) -> SqlChangeSet:
    old = Reservoir(get_reservoir(name, cs.operations[0]['id']))

    redo_sql = f"delete from coordinates where node = {old.f_id};"
    redo_sql += f"\ndelete from reservoirs where id = {old.f_id};"
    redo_sql += f"\ndelete from _node where id = {old.f_id};"

    undo_sql = f"insert into _node (id, type) values ({old.f_id}, {old.f_type});"
    undo_sql += f"\ninsert into reservoirs (id, head, pattern) values ({old.f_id}, {old.f_head}, {old.f_pattern});"
    undo_sql += f"\ninsert into coordinates (node, coord) values ({old.f_id}, {old.f_coord});"

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


class InpReservoir:
    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.head = float(tokens[1])
        self.pattern = str(tokens[2]) if num_without_desc >= 3 else None
        self.desc = str(tokens[-1]) if has_desc else None


def inp_in_reservoir(section: list[str]) -> ChangeSet:
    cs = ChangeSet()
    for s in section:
        # skip comment
        if s.startswith(';'):
            continue
        obj = InpReservoir(s)
        cs.append(g_add_prefix | {'type': 'reservoir', 'id': obj.id, 'head': obj.head, 'pattern': obj.pattern})
    return cs


def inp_out_reservoir(name: str) -> list[str]:
    lines = []
    objs = read_all(name, 'select * from reservoirs')
    for obj in objs:
        id = obj['id']
        head = obj['head']
        pattern = obj['pattern'] if obj['pattern'] != None else ''
        desc = ';'
        lines.append(f'{id} {head} {pattern} {desc}')
    return lines
