from .s1_title import *
from .s2_junctions import *
from .s3_reservoirs import *
from .s4_tanks import *
from .s5_pipes import *
from .s6_pumps import *
from .s7_valves import *
from .s9_demands import *
from .s10_status import *
from .s11_patterns import *
from .s12_curves import *
from .s16_emitters import *
from .s21_times import *
from .s23_options import *


def execute_add_command(name: str, cs: ChangeSet) -> ChangeSet:
    type = cs.operations[0]['type']

    if type == JUNCTION:
        return add_junction(name, cs)
    elif type == RESERVOIR:
        return add_reservoir(name, cs)
    elif type == TANK:
        return add_tank(name, cs)
    elif type == PIPE:
        return add_pipe(name, cs)
    elif type == PUMP:
        return add_pump(name, cs)
    elif type == VALVE:
        return add_valve(name, cs)

    return ChangeSet()


def execute_update_command(name: str, cs: ChangeSet) -> ChangeSet:
    type = cs.operations[0]['type']

    if type == 'title':
        return set_title(name, cs)
    if type == JUNCTION:
        return set_junction(name, cs)
    elif type == RESERVOIR:
        return set_reservoir(name, cs)
    elif type == TANK:
        return set_tank(name, cs)
    elif type == PIPE:
        return set_pipe(name, cs)
    elif type == PUMP:
        return set_pump(name, cs)
    elif type == VALVE:
        return set_valve(name, cs)
    elif type == 'demand':
        return set_demand(name, cs)
    elif type == 'status':
        return set_status(name, cs)
    elif type == PATTERN:
        return set_pattern(name, cs)
    elif type == CURVE:
        return set_curve(name, cs)
    elif type == 'emitter':
        return set_emitter(name, cs)
    elif type == 'time':
        return set_time(name, cs)
    elif type == 'option':
        return set_option(name, cs)

    return ChangeSet()


def execute_delete_command(name: str, cs: ChangeSet) -> ChangeSet:
    type = cs.operations[0]['type']

    if type == JUNCTION:
        return delete_junction(name, cs)
    elif type == RESERVOIR:
        return delete_reservoir(name, cs)
    elif type == TANK:
        return delete_tank(name, cs)
    elif type == PIPE:
        return delete_pipe(name, cs)
    elif type == PUMP:
        return delete_pump(name, cs)
    elif type == VALVE:
        return delete_valve(name, cs)

    return ChangeSet()


def execute_batch_commands(name: str, cs: ChangeSet) -> ChangeSet:
    result = ChangeSet()

    try:
        for op in cs.operations:
            operation = op['operation']
            if operation == API_ADD:
                result.merge(execute_add_command(name, ChangeSet(op)))
            elif operation == API_UPDATE:
                result.merge(execute_update_command(name, ChangeSet(op)))
            elif operation == API_DELETE:
                result.merge(execute_delete_command(name, ChangeSet(op)))
    except:
        pass

    return result
