from orangescape.model.engine.engineconstants import WORKFLOW, AND_PROCESS, OR_PROCESS, REAL_OR_PROCESS, GOTO
from orangescape.model.engine.execution.ExecutionTree import ExecutionTree
import appconfig as config


if config.env==config.SL:
    process_module_pkg = 'ProcessEngine.%sProcessNode'
    action_module_pkg = '%sCommand.%sProcessNode'
else:
    process_module_pkg = 'orangescape.model.engine.execution.ProcessEngine.%sProcessNode'
    action_module_pkg = 'orangescape.model.engine.execution.actions.%sCommand.%sProcessNode'


def getContextBranch(activity):
    branch = activity.getBranch()
    if branch.getSheetMetadata() is not None:
        return branch
    if branch.getNodeType()==AND_PROCESS or branch.getNodeType()==REAL_OR_PROCESS:
        return branch
    return getContextBranch(branch.getActivityDefinition())

def getProcessCell_PrefixName(activity):
    context_branch = getContextBranch(activity)
    if context_branch.getSheetMetadata() is not None:
        prefix_name = ''
    else:
        prefix_name = context_branch.getSheetId()+'_'
    return prefix_name

def getRootBranch(activity):
    branch = activity.getBranch()
    if branch.getSheetMetadata():
        return branch
    return getRootBranch(branch.getActivityDefinition())

def getInputportByParamName(activityDefinition, paramName):
    ipPortList = [ipPort for ipPort in activityDefinition.getInputportMetadataList() if ipPort.getParamName()==paramName]
    if ipPortList:
        return ipPortList.pop()
    return None

def getProcessNode(component, activitydef, sheet):
    from orangescape.model.server.util.ServerUtil import _get_class
    if activitydef.getProcessType()==WORKFLOW or activitydef.getNodeType()==OR_PROCESS or activitydef.getNodeType()==AND_PROCESS or activitydef.getNodeType()==GOTO or activitydef.getNodeType()==REAL_OR_PROCESS:
        nextProcessNode = _get_class(process_module_pkg%(activitydef.getNodeType()))(component, sheet, activitydef)
    else:
        nextProcessNode = _get_class(action_module_pkg%(activitydef.getNodeType(), activitydef.getNodeType()))(component, sheet, activitydef)
    return nextProcessNode

def getActionByName(metadata, name):
    branchList = metadata.getBranchList()
    bList = [branch for branch in branchList if branch.getSheetName()==name]
    if len(bList)>0:
        return bList.pop()
    raise Exception('%s not found in %s'%(name, metadata.getSheetName()))

def getAssignedUser(session, sheet, activityDefinition):
    if activityDefinition.containsFormula():
        et = ExecutionTree(session)
        eMailId = et.executeFormula(activityDefinition.getFormulaList()[0], sheet)
    else:
        eMailId = activityDefinition.getUser()
    if eMailId:
        return eMailId.strip()
    return None