"""
Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)

Date:   Tue Oct 11 13:05:26 2016

Model author: Sadaf Mustafiz and Bruno Barroca and Claudio Gomes
Model name:   CBDSimulator
Model description:
SCCD HUTN model of a CBD simulator
"""

from sccd.runtime.statecharts_core import *
from sccd.runtime.libs.ui import *
from sccd.runtime.libs.utils import *
from CBD_Controller import CBDController
import Options

# package "CBDSimulator"

class CBDSimulator(RuntimeClassBase):
    def __init__(self, controller, options, model):
        RuntimeClassBase.__init__(self, controller)
        
        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
        self.semantics.priority = StatechartSemantics.SourceParent
        self.semantics.concurrency = StatechartSemantics.Single
        
        # build Statechart structure
        self.build_statechart_structure()
        
        # user defined attributes
        self.iteration = None
        self.cbdController = None
        self.currentCompIdx = None
        self.clock = None
        self.model = None
        self.depGraph = None
        self.strongComponentList = None
        self.delta = None
        
        # call user defined constructor
        CBDSimulator.user_defined_constructor(self, options, model)
    
    def user_defined_constructor(self, options, model):
        self.options = options
        self.delta = self.options.getDeltaT()
        self.model = model
    
    def user_defined_destructor(self):
        pass
    
    
    # user defined method
    def maxIterationsReached(self):
        return self.iteration >= self.options.getMaxIterations()
    
    
    # user defined method
    def currentComponentIsCycle(self):
        return self.cbdController.componentIsCycle(self.strongComponentList[self.currentCompIdx], self.depGraph)
    
    
    # user defined method
    def hasNextStrongComponent(self):
        return (self.currentCompIdx) < len(self.strongComponentList)
    
    
    # user defined method
    def computeBlock(self):
        if self.currentComponentIsCycle():
        	self.cbdController.computeNextAlgebraicLoop(self.strongComponentList[self.currentCompIdx], self.iteration)
        else:
        	self.cbdController.computeNextBlock(self.strongComponentList[self.currentCompIdx], self.iteration)
    
    
    # user defined method
    def advanceTime(self):
        self.iteration = self.iteration + 1
        self.clock = self.clock + self.delta
        self.cbdController.advanceTimeStep()
    
    
    # builds Statechart structure
    def build_statechart_structure(self):
        
        # state <root>
        self.states[""] = State(0, self)
        
        # state /DoSimulation
        self.states["/DoSimulation"] = State(1, self)
        
        # state /DoSimulation/MacroStepPrepared
        self.states["/DoSimulation/MacroStepPrepared"] = State(2, self)
        
        # state /DoSimulation/MicroStepPrepared
        self.states["/DoSimulation/MicroStepPrepared"] = State(3, self)
        
        # state /DoSimulation/MicroStepProcessed
        self.states["/DoSimulation/MicroStepProcessed"] = State(4, self)
        
        # state /Started
        self.states["/Started"] = State(5, self)
        
        # state /CheckTermination
        self.states["/CheckTermination"] = State(6, self)
        
        # state /CheckTermination/MacroStepProcessed
        self.states["/CheckTermination/MacroStepProcessed"] = State(7, self)
        
        # state /End
        self.states["/End"] = State(8, self)
        
        # state /Initialized
        self.states["/Initialized"] = State(9, self)
        
        # add children
        self.states[""].addChild(self.states["/DoSimulation"])
        self.states[""].addChild(self.states["/Started"])
        self.states[""].addChild(self.states["/CheckTermination"])
        self.states[""].addChild(self.states["/End"])
        self.states[""].addChild(self.states["/Initialized"])
        self.states["/DoSimulation"].addChild(self.states["/DoSimulation/MacroStepPrepared"])
        self.states["/DoSimulation"].addChild(self.states["/DoSimulation/MicroStepPrepared"])
        self.states["/DoSimulation"].addChild(self.states["/DoSimulation/MicroStepProcessed"])
        self.states["/CheckTermination"].addChild(self.states["/CheckTermination/MacroStepProcessed"])
        self.states[""].fixTree()
        self.states[""].default_state = self.states["/Started"]
        self.states["/DoSimulation"].default_state = self.states["/DoSimulation/MacroStepPrepared"]
        self.states["/CheckTermination"].default_state = self.states["/CheckTermination/MacroStepProcessed"]
        
        # transition /DoSimulation/MacroStepPrepared
        _DoSimulation_MacroStepPrepared_0 = Transition(self, self.states["/DoSimulation/MacroStepPrepared"], [self.states["/DoSimulation/MicroStepProcessed"]])
        _DoSimulation_MacroStepPrepared_0.setAction(self._DoSimulation_MacroStepPrepared_0_exec)
        _DoSimulation_MacroStepPrepared_0.setTrigger(None)
        self.states["/DoSimulation/MacroStepPrepared"].addTransition(_DoSimulation_MacroStepPrepared_0)
        
        # transition /DoSimulation/MicroStepPrepared
        _DoSimulation_MicroStepPrepared_0 = Transition(self, self.states["/DoSimulation/MicroStepPrepared"], [self.states["/DoSimulation/MicroStepProcessed"]])
        _DoSimulation_MicroStepPrepared_0.setAction(self._DoSimulation_MicroStepPrepared_0_exec)
        _DoSimulation_MicroStepPrepared_0.setTrigger(None)
        self.states["/DoSimulation/MicroStepPrepared"].addTransition(_DoSimulation_MicroStepPrepared_0)
        
        # transition /DoSimulation/MicroStepProcessed
        _DoSimulation_MicroStepProcessed_0 = Transition(self, self.states["/DoSimulation/MicroStepProcessed"], [self.states["/CheckTermination"]])
        _DoSimulation_MicroStepProcessed_0.setAction(self._DoSimulation_MicroStepProcessed_0_exec)
        _DoSimulation_MicroStepProcessed_0.setTrigger(None)
        _DoSimulation_MicroStepProcessed_0.setGuard(self._DoSimulation_MicroStepProcessed_0_guard)
        self.states["/DoSimulation/MicroStepProcessed"].addTransition(_DoSimulation_MicroStepProcessed_0)
        _DoSimulation_MicroStepProcessed_1 = Transition(self, self.states["/DoSimulation/MicroStepProcessed"], [self.states["/DoSimulation/MicroStepPrepared"]])
        _DoSimulation_MicroStepProcessed_1.setAction(self._DoSimulation_MicroStepProcessed_1_exec)
        _DoSimulation_MicroStepProcessed_1.setTrigger(None)
        _DoSimulation_MicroStepProcessed_1.setGuard(self._DoSimulation_MicroStepProcessed_1_guard)
        self.states["/DoSimulation/MicroStepProcessed"].addTransition(_DoSimulation_MicroStepProcessed_1)
        
        # transition /Started
        _Started_0 = Transition(self, self.states["/Started"], [self.states["/Initialized"]])
        _Started_0.setAction(self._Started_0_exec)
        _Started_0.setTrigger(None)
        self.states["/Started"].addTransition(_Started_0)
        
        # transition /CheckTermination/MacroStepProcessed
        _CheckTermination_MacroStepProcessed_0 = Transition(self, self.states["/CheckTermination/MacroStepProcessed"], [self.states["/DoSimulation"]])
        _CheckTermination_MacroStepProcessed_0.setAction(self._CheckTermination_MacroStepProcessed_0_exec)
        _CheckTermination_MacroStepProcessed_0.setTrigger(None)
        _CheckTermination_MacroStepProcessed_0.setGuard(self._CheckTermination_MacroStepProcessed_0_guard)
        self.states["/CheckTermination/MacroStepProcessed"].addTransition(_CheckTermination_MacroStepProcessed_0)
        _CheckTermination_MacroStepProcessed_1 = Transition(self, self.states["/CheckTermination/MacroStepProcessed"], [self.states["/End"]])
        _CheckTermination_MacroStepProcessed_1.setAction(self._CheckTermination_MacroStepProcessed_1_exec)
        _CheckTermination_MacroStepProcessed_1.setTrigger(None)
        _CheckTermination_MacroStepProcessed_1.setGuard(self._CheckTermination_MacroStepProcessed_1_guard)
        self.states["/CheckTermination/MacroStepProcessed"].addTransition(_CheckTermination_MacroStepProcessed_1)
        
        # transition /Initialized
        _Initialized_0 = Transition(self, self.states["/Initialized"], [self.states["/CheckTermination"]])
        _Initialized_0.setAction(self._Initialized_0_exec)
        _Initialized_0.setTrigger(None)
        self.states["/Initialized"].addTransition(_Initialized_0)
    
    def _DoSimulation_MacroStepPrepared_0_exec(self, parameters):
        print('Going to MicroStepProcessed... ')
    
    def _DoSimulation_MicroStepPrepared_0_exec(self, parameters):
        print('Going to MicroStepProcessed...')
        self.computeBlock()
        self.currentCompIdx = self.currentCompIdx + 1
    
    def _DoSimulation_MicroStepProcessed_0_exec(self, parameters):
        print('Going to CheckTermination and advancing time... ')
        self.advanceTime()
        print(self.clock)
        print(self.iteration)
    
    def _DoSimulation_MicroStepProcessed_0_guard(self, parameters):
        return not self.hasNextStrongComponent()
    
    def _DoSimulation_MicroStepProcessed_1_exec(self, parameters):
        print('Going to MicroStepPrepared')
    
    def _DoSimulation_MicroStepProcessed_1_guard(self, parameters):
        return self.hasNextStrongComponent()
    
    def _Started_0_exec(self, parameters):
        print('Going to Initialized... ')
        print('Performing initialization...')
        self.iteration = 0
        self.clock = 0
        self.cbdController = CBDController(self.model, self.delta)
        self.cbdController.initSimulation()
        print('Performing initialization... DONE')
    
    def _CheckTermination_MacroStepProcessed_0_exec(self, parameters):
        print('Going to DoSimulation... ')
        self.currentCompIdx = 0
        self.depGraph = self.cbdController.createDepGraph(self.iteration)
        self.strongComponentList = self.cbdController.createStrongComponents(self.depGraph, self.iteration)
    
    def _CheckTermination_MacroStepProcessed_0_guard(self, parameters):
        return not self.maxIterationsReached()
    
    def _CheckTermination_MacroStepProcessed_1_exec(self, parameters):
        print('Going to End... ')
    
    def _CheckTermination_MacroStepProcessed_1_guard(self, parameters):
        return self.maxIterationsReached()
    
    def _Initialized_0_exec(self, parameters):
        print('Going to CheckTermination... ')
    
    def initializeStatechart(self):
        # enter default state
        self.default_targets = self.states["/Started"].getEffectiveTargetStates()
        RuntimeClassBase.initializeStatechart(self)

class ObjectManager(ObjectManagerBase):
    def __init__(self, controller):
        ObjectManagerBase.__init__(self, controller)
    
    def instantiate(self, class_name, construct_params):
        if class_name == "CBDSimulator":
            instance = CBDSimulator(self.controller, construct_params[0], construct_params[1])
            instance.associations = {}
        else:
            raise Exception("Cannot instantiate class " + class_name)
        return instance

class Controller(ThreadsControllerBase):
    def __init__(self, options, model, keep_running = None, behind_schedule_callback = None):
        if keep_running == None: keep_running = True
        if behind_schedule_callback == None: behind_schedule_callback = None
        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
        self.object_manager.createInstance("CBDSimulator", [options, model])