import logging
from orangescape.model.engine.execution.ProcessEngine import ProcessNode
from orangescape.model.engine.execution.ProcessUtil import getContextBranch, getProcessCell_PrefixName, getRootBranch
from orangescape.model.engine.engineconstants import WORKFLOW, AND_PROCESS, OR_PROCESS, REAL_OR_PROCESS, GOTO
from orangescape.model.engine.exception.Error import ProcessEngineError
from orangescape.model.engine.exception.ErrorMessage import Engine3000, Engine3002

class SubmitProcessNode(ProcessNode):

    def enter(self):
        metadata = self.sheet.getSheetMetadata()

        submitFromActId = self.args.get('Submit-From')

        if submitFromActId:
            submitFromActivity = metadata.getActivityDefinitionById(submitFromActId)
            prefix_name = getProcessCell_PrefixName(submitFromActivity)

            currentActivity = metadata.getActivityDefinitionById(self.sheet.getValue(prefix_name+'Status'))
            if not currentActivity or currentActivity.getSheetId() != submitFromActId:
                if self.args.get('Suppress-Error'):
                    logging.warn('Submit command failed for the instance')
                    logging.warn(Engine3000 %(self.sheet.getSheetId(), self.sheet.getSheetName(), metadata.getSheetName(), submitFromActivity.getSheetName()))
                else:
                    raise ProcessEngineError, Engine3000 %(self.sheet.getSheetId(), self.sheet.getSheetName(), metadata.getSheetName(),
                                                           submitFromActivity.getSheetName())
            else:
                self.component.submit(self.sheet, submitFromActivity)
        else:
            rootProcessAct = metadata.getActivityDefinitionById(self.sheet.getValue('Status'))
            if rootProcessAct.getSequenceNo() == 1.0:# or rootProcessAct.getNodeType() == WORKFLOW:
                submitFromActivity = rootProcessAct
            else:
                modifiedInId = self.session.getModifiedIn()
                modifiedInActivity = metadata.getActivityDefinitionById(modifiedInId)
                if modifiedInActivity.getBelongingSheetId() != metadata.getSheetId():
                    raise ProcessEngineError, Engine3002 %(self.sheet.getSheetId(), self.sheet.getSheetName(), metadata.getSheetName(), getRootBranch(self.activityDefinition).getSheetName())
                submitFromActivity = modifiedInActivity

            self.component.submit(self.sheet, submitFromActivity)