import logging
from orangescape.model.engine.execution.ProcessEngine import ProcessNode
from orangescape.model.engine.execution.ExecutionTree import ExecutionTree

class CallParentActionProcessNode(ProcessNode):

    def enter(self):
        referenceCell = self.args.get('Reference-Cell')
        actionId = self.args.get('ParentAction-Name')
        parentMetadata = referenceCell.getReferredSheetMetadata()

        if self.sheet.get(referenceCell) is not None and str(self.sheet.get(referenceCell)).strip() != '':
            contextCell = self.args.get('Context-CellName')

            params = {}
            for opPort in self.activityDefinition.getOutputportMetadataList():
                if self.args.has_key(opPort.getParamName()):
                    value = self.args[opPort.getParamName()]
                    cell = opPort.getCellMetadata()
                    if cell and not cell.isFormula():
                        params[opPort.getCellMetadata().getCellName()] = value
                else:
                    """Value might not be specified or it might be None"""

            parentSheet = self.session.get(self.sheet.get(referenceCell), parentMetadata)
            if params:
                logging.info('CallParent: from %s(%s) to %s(%s) updating values %s'%(self.sheet.getSheetMetadata().getSheetName(), self.sheet.getSheetId(), parentMetadata.getSheetName(), parentSheet.getSheetId(), params))
                self.component.update(parentSheet, params)
            if contextCell:
                contextCell = parentMetadata.getCellMetadataById(contextCell)
                self.component.update(parentSheet, {contextCell.getCellName():self.sheet.getSheetId()})

            parentAction = parentMetadata.getBranchById(actionId)
            if parentAction:
                logging.debug('Calling parent action %s for the parent sheet %s from the child %s'%(parentAction.getSheetName(), parentSheet.getSheetId(), self.sheet.getSheetId()))
                self.component.executeAction(parentSheet, parentAction)
            else:
                logging.info('CallParentActionCommand: Coult not find the parent action %s for the model %s from the child model %s for the instance %s'%(actionId, parentMetadata.getSheetName(), self.sheet.getSheetMetadata().getSheetName(), self.sheet.getSheetId()))

            if contextCell:
                self.component.update(parentSheet, {contextCell.getCellName():None})
