from .operation import *


def get_demand_schema(name: str) -> dict[str, dict[str, Any]]:
    return { 'junction' : {'type': 'str'  , 'optional': False , 'readonly': True },
             'demands'  : {'type': 'list' , 'optional': False , 'readonly': False, 
                           'element': { 'demand'  : {'type': 'float' , 'optional': False , 'readonly': False }, 
                                        'patten'  : {'type': 'str'   , 'optional': True ,  'readonly': False },
                                        'category': {'type': 'str'   , 'optional': True ,  'readonly': False }}}}


def get_demand(name: str, junction: str) -> dict[str, Any]:
    des = read_all(name, f"select * from demands where junction = '{junction}'")
    ds = []
    for r in des:
        d = {}
        d['demand'] = float(r['demand'])
        d['pattern'] = str(r['pattern']) if r['pattern'] != None else None
        d['category'] = str(r['category']) if r['category'] != None else None
        ds.append(d)
    return { 'junction': junction, 'demands': ds }

# { 'operation': 'update', 'type': 'demand', 'junction': 'j1', 'demands': [{'demand': 0.0, 'patten': None, 'category': None}] }
def set_demand(name: str, cs: ChangeSet) -> ChangeSet:
    junction = cs.operations[0]['junction']
    old = get_demand(name, junction)
    new = { 'junction': junction, 'demands': [] }

    f_junction = f"'{junction}'"

    # TODO: transaction ?
    redo_sql = f"delete from demands where junction = {f_junction};"
    for r in cs.operations[0]['demands']:
        demand = float(r['demand'])
        pattern = str(r['pattern']) if 'pattern' in r and r['pattern'] != None else None
        category = str(r['category']) if 'category' in r and r['category'] != None else None
        f_demand = demand
        f_pattern = f"'{pattern}'" if pattern != None else 'null'
        f_category = f"'{category}'" if category != None else 'null'
        redo_sql += f"\ninsert into demands (junction, demand, pattern, category) values ({f_junction}, {f_demand}, {f_pattern}, {f_category});"
        new['demands'].append({ 'demand': demand, 'pattern': pattern, 'category': category })

    undo_sql = f"delete from demands where junction = {f_junction};"
    for r in old['demands']:
        demand = float(r['demand'])
        pattern = str(r['pattern'])
        category = str(r['category'])
        f_demand = demand
        f_pattern = f"'{pattern}'" if pattern != None else 'null'
        f_category = f"'{category}'" if category != None else 'null'
        undo_sql += f"\ninsert into demands (junction, demand, pattern, category) values ({f_junction}, {f_demand}, {f_pattern}, {f_category});"
    
    redo_cs = g_update_prefix | { 'type': 'demand' } | new
    undo_cs = g_update_prefix | { 'type': 'demand' } | old

    return execute_command(name, redo_sql, undo_sql, redo_cs, undo_cs)
