import logging
from orangescape.model.engine.execution.ProcessEngine import ProcessNode
from orangescape.model.engine.execution.ExecutionTree import ExecutionTree
from orangescape.model.server.Interface import BaseNode
import appconfig as config

class CallChildActionProcessNode(ProcessNode):

    def enter(self):
        referenceCell = self.args.get('Reference-Cell')
        actionId = self.args.get('CallAction-Name')
        searchCriteria = self.args.get('Child-Search-Criteria')
        childMetadata = referenceCell.getSheetMetadata()
        orderBy = self.args.get('Order-By') or childMetadata.getPublicCellMetadata('CreatedAt')
        isReverse = self.args.get('Sort-By') or 0.0

        if searchCriteria is None:
            searchCriteria = self.args.get('Search-Criteria')

        childList = None
        if searchCriteria:
            rootNode = BaseNode()
            et = ExecutionTree(self.session)
            et.resolveRHS(searchCriteria, self.sheet, rootNode)
            rootNode.formula = searchCriteria.getFormula()
            childList = self.session.filter(self.sheet, referenceCell, rootNode)
#            logging.info('Call child with criteria result %s'%([c.getSheetId() for c in childList]))
        else:
            childList = self.session.getList(self.sheet, referenceCell)


        childList.sort(lambda x, y:cmp(x.get(orderBy), y.get(orderBy)), reverse=isReverse)

        if config.env != config.SL and logging.getLogger().level == logging.DEBUG:
            logging.debug('Executing call child for the instances %s'%([c.getSheetId() for c in childList]))

        childAction = childMetadata.getBranchById(actionId)

        for child in childList:
            logging.debug('Calling child action %s for the instance %s'%(childAction.getSheetName(), child.getSheetName()))
            self.component.executeAction(child, childAction)