include "primitives.alh"
include "services.alh"
include "modelling.alh"
include "object_operations.alh"
include "utils.alh"
include "io.alh"
include "typing.alh"

Boolean function main(model : Element):
    log("Translating DEVS to string representation!")

    String model_rep
    Element all_atomics
    Element curr_atomic
    Element all_coupleds
    Element curr_coupled
    Element string_element
    Element all_ports
    Element all_submodels
    Element curr_port
    Element curr_submodel
    Element out_channels
    Element curr_channel
    Element possible_parent
    Element parent
    String curr_port_name
    String curr_port_type
    String curr_submodel_name
    String curr_submodel_type

    model_rep = "\nfrom DEVS import *\nfrom infinity import INFINITY\n\n"

    all_atomics = allInstances(model, "ParallelDEVS/AtomicDEVSBlock")
    while (read_nr_out(all_atomics) > 0):
        curr_atomic = set_pop(all_atomics)
        model_rep = ((model_rep + "class ") + cast_string(read_attribute(model, curr_atomic, "name"))) + "(AtomicDEVS):\n"
        model_rep = ((model_rep + "\tdef __init__(self, name=") + cast_value(read_attribute(model, curr_atomic, "name"))) + "):\n"
        model_rep = model_rep + "\t\tAtomicDEVS.__init__(self, name)\n"
        model_rep = model_rep + "\t\tself.state = self.initialState()\n"
        model_rep = model_rep + "\t\tself.my_ports = {"
        all_ports = allAssociationDestinations(model, curr_atomic, "ParallelDEVS/DEVSBlockToPort")
        while (read_nr_out(all_ports) > 0):
            curr_port = set_pop(all_ports)
            curr_port_name = cast_value(read_attribute(model, curr_port, "name"))
            curr_port_type = read_type(model, curr_port)
            if (curr_port_type == "ParallelDEVS/InputPort"):
                model_rep = (((model_rep + curr_port_name) + ": self.addInPort(") + curr_port_name) + ")"
            if (curr_port_type == "ParallelDEVS/OutputPort"):
                model_rep = (((model_rep + curr_port_name) + ": self.addOutPort(") + curr_port_name) + ")"
            if (read_nr_out(all_ports) > 0):
                model_rep = model_rep + ", "
        model_rep = model_rep + "}\n"
        model_rep = model_rep + "\tdef initialState(self):\n" + cast_string(read_attribute(model, curr_atomic, "initialState")) + "\n"
        model_rep = ((model_rep + "\tdef timeAdvance(self):\n") + cast_string(read_attribute(model, curr_atomic, "timeAdvance"))) + "\n"
        model_rep = ((model_rep + "\tdef outputFnc(self):\n") + cast_string(read_attribute(model, curr_atomic, "outputFnc"))) + "\n"
        model_rep = ((model_rep + "\tdef intTransition(self):\n") + cast_string(read_attribute(model, curr_atomic, "intTransition"))) + "\n"
        model_rep = ((model_rep + "\tdef extTransition(self, my_inputs):\n") + cast_string(read_attribute(model, curr_atomic, "extTransition"))) + "\n"
        model_rep = ((model_rep + "\tdef confTransition(self, my_inputs):\n") + cast_string(read_attribute(model, curr_atomic, "confTransition"))) + "\n"

    all_coupleds = allInstances(model, "ParallelDEVS/CoupledDEVSBlock")
    while (read_nr_out(all_coupleds) > 0):
        curr_coupled = set_pop(all_coupleds)
        model_rep = ((model_rep + "class ") + cast_string(read_attribute(model, curr_coupled, "name"))) + "(CoupledDEVS):\n"
        model_rep = ((model_rep + "\tdef __init__(self, name=") + cast_value(read_attribute(model, curr_coupled, "name"))) + "):\n"
        model_rep = model_rep + "\t\tCoupledDEVS.__init__(self, name)\n"
        model_rep = model_rep + "\t\tself.my_ports = {"
        all_ports = allAssociationDestinations(model, curr_coupled, "ParallelDEVS/DEVSBlockToPort")
        while (read_nr_out(all_ports) > 0):
            curr_port = set_pop(all_ports)
            curr_port_name = cast_value(read_attribute(model, curr_port, "name"))
            curr_port_type = read_type(model, curr_port)
            log(curr_port_type)
            if (curr_port_type == "ParallelDEVS/InputPort"):
                model_rep = (((model_rep + curr_port_name) + ": self.addInPort(") + curr_port_name) + ")"
            if (curr_port_type == "ParallelDEVS/OutputPort"):
                model_rep = (((model_rep + curr_port_name) + ": self.addOutPort(") + curr_port_name) + ")"
            if (read_nr_out(all_ports) > 0):
                model_rep = model_rep + ", "
        model_rep = model_rep + "}\n"
        model_rep = model_rep + "\t\tself.submodels = {"
        all_submodels = allAssociationDestinations(model, curr_coupled, "ParallelDEVS/SubModel")
        while (read_nr_out(all_submodels) > 0):
            curr_submodel = set_pop(all_submodels)
            curr_submodel_name = cast_value(read_attribute(model, curr_submodel, "name"))
            curr_submodel_type = cast_string(read_attribute(model, curr_submodel, "type"))
            model_rep = ((((((model_rep + curr_submodel_name) + ": self.addSubModel(") + curr_submodel_type) + "(name=") + curr_submodel_name) + ")") + ")"
            if (read_nr_out(all_submodels) > 0):
                model_rep = model_rep + ", "
        model_rep = model_rep + "}\n"
        all_ports = allAssociationDestinations(model, curr_coupled, "ParallelDEVS/DEVSBlockToPort")
        while (read_nr_out(all_ports) > 0):
            curr_port = set_pop(all_ports)
            out_channels = allAssociationDestinations(model, curr_port, "ParallelDEVS/Channel")
            while (read_nr_out(out_channels) > 0):
                curr_channel = set_pop(out_channels)
                parent = set_pop(allAssociationOrigins(model, curr_channel, "ParallelDEVS/DEVSInstanceToPort"))
                model_rep = ((((((model_rep + "\t\tself.connectPorts(self.my_ports[") + cast_value(read_attribute(model, curr_port, "name"))) + "], self.submodels[") + cast_value(read_attribute(model, parent, "name"))) + "].my_ports[") + cast_value(read_attribute(model, curr_channel, "name"))) + "])\n"
        all_submodels = allAssociationDestinations(model, curr_coupled, "ParallelDEVS/SubModel")
        while (read_nr_out(all_submodels) > 0):
            curr_submodel = set_pop(all_submodels)
            curr_submodel_name = cast_value(read_attribute(model, curr_submodel, "name"))
            log(curr_submodel_name)
            all_ports = allAssociationDestinations(model, curr_submodel, "ParallelDEVS/DEVSInstanceToPort")
            while (read_nr_out(all_ports) > 0):
                curr_port = set_pop(all_ports)
                out_channels = allAssociationDestinations(model, curr_port, "ParallelDEVS/Channel")
                log(cast_value(read_nr_out(out_channels)))
                while (read_nr_out(out_channels) > 0):
                    curr_channel = set_pop(out_channels)
                    possible_parent = allAssociationOrigins(model, curr_channel, "ParallelDEVS/DEVSInstanceToPort")
                    if (read_nr_out(possible_parent) == 0):
                        model_rep = ((((((model_rep + "\t\tself.connectPorts(self.submodels[") + curr_submodel_name) + "].my_ports[") + cast_value(read_attribute(model, curr_port, "name"))) + "], self.my_ports[") + cast_value(read_attribute(model, curr_channel, "name"))) + "])\n"
                    else:
                        parent = set_pop(possible_parent)
                        model_rep = ((((((((model_rep + "\t\tself.connectPorts(self.submodels[") + curr_submodel_name) + "].my_ports[") + cast_value(read_attribute(model, curr_port, "name"))) + "], self.submodels[") + cast_value(read_attribute(model, parent, "name"))) + "].my_ports[") + cast_value(read_attribute(model, curr_channel, "name"))) + "])\n"
        model_rep = model_rep + "\n"

    log("Printing model_rep...")
    log("\n" + model_rep)

	String port
    String the_input
    String devs_model
	port = comm_connect("pypdevs_simulator")
        
    log("(PDEVS) task name = " + get_taskname())
    log("(PDEVS) Sending model...")
    comm_set(port, model_rep)
    log("(PDEVS) " + port)
    
    while (True):
        if (comm_hasInput(port)):
            log(cast_value(has_input()))
            the_input = comm_get(port)
            log("(PDEVS) Got input from simulator!")
            log("(PDEVS) " + the_input)
            output(the_input)

        if (has_input()):
            the_input = input()
            log("(PDEVS) Got input from console/ps simulator!")
            log("(PDEVS) " + cast_value(the_input))
            if (is_physical_string(the_input)):
                comm_set(port, the_input)
				if (the_input == "[\"exit\"]"):
					break!
            else:
                comm_set(port, cast_value(the_input))
        sleep(0.05)

	return True!
