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

from orangescape.model.engine.exception.Error import CustomCommandError
from orangescape.model.engine.exception.ErrorMessage import Action1000
from orangescape.model.server.util.metadatautil import getRootBranch

from orangescape.model.server.util.ServerUtil import __resolve_search_criteria__
import logging

class RCallProcessNode(ProcessNode):

    def enter(self):
        modelId = self.args.get('Model-Name')
        if not modelId:
            'Calling Model name not specified for call Command while executing the action %s in the model %s for the instance %s'%()
            raise CustomCommandError, Action1000 %(getRootBranch(self.activityDefinition.getBranch(), self.sheet.getSheetMetadata().getSheetName(), self.sheet.getSheetId()))
        actionId = self.args.get('CallAction-Name')

        searchCriteria = self.args.get('Search-Criteria')
        if searchCriteria:
            limit = int(self.args.get('Limit') or 1000)
            searchList = __resolve_search_criteria__(self.session, self.sheet, searchCriteria, limit)
            if logging.getLogger().level == logging.DEBUG:
                logging.debug('RCall Query Results: %s'%([instance.getSheetId() for instance in searchList]))
            contextCell = self.args.get('Context-CellName')
            rMetadata = self.getSheetMetadataById(modelId)
            rAction = rMetadata.getBranchById(actionId)
            for rSheet in searchList:
                if contextCell:
                    if isinstance(contextCell, str) or isinstance(contextCell, unicode):
                        contextCell = rMetadata.getCellMetadataById(contextCell)
                    self.component.update(rSheet, {contextCell.getCellName():self.sheet.getSheetId()})
                self.component.executeAction(rSheet, rAction)
                if contextCell:
                    self.component.update(rSheet, {contextCell.getCellName():None})
        else:
            logging.warn('No Search-Criteria found for executing RCall for the instance %s'%self.sheet.getSheetId())
