#!/usr/bin/env python

import copy
import time
import roush


class AgentBackend(roush.backends.Backend):
    def __init__(self):
        super(AgentBackend, self).__init__(__file__)

    def additional_constraints(self):
        # this is probably a bit viscious.
        return None

    def add_backend(self, api, node_id, **kwargs):
        self.logger.debug('adding agent backend')

        roush.webapp.ast.apply_expression(
            node_id, 'facts.backends := union(facts.backends, "agent")', api)

        return True

    def run_task(self, api, node_id, **kwargs):
        action = kwargs['action']
        payload = kwargs['payload']
        adventure_globals = []

        # payload = dict([(x, kwargs[x]) for x in kwargs if x != 'action'])

        print '******************** kwargs: %s' % kwargs

        self.logger.debug('run_task: got kwargs %s' % kwargs)

        # push global variables, unless they have been specifically
        # set in the task payload.
        if 'globals' in kwargs:
            adventure_globals = kwargs['globals']
            # for k, v in globals.items():
            #     if not k in payload:
            #         payload[k] = v

        ns = copy.deepcopy(payload)
        ns.update(copy.deepcopy(adventure_globals))

        for k, v in payload.items():
            print(' ***** applying "%s" on "%s"' % (v, ns))
            payload[k] = roush.webapp.ast.apply_expression(ns, v, api)
            print(' ***** ...resulting in %s' % payload[k])

        task = api._model_create('tasks', {'node_id': node_id,
                                           'action': action,
                                           'payload': payload})

        self.logger.debug('added task as id %s' % task['id'])

        while task['state'] not in ['timeout', 'cancelled', 'done']:
            time.sleep(5)
            task = api._model_get_by_id('tasks', task['id'])

        return True

@@ -755,66 +755,8 @@
 %5D)%0A%0A
-        print '******************** kwargs: %25s' %25 kwargs%0A%0A
     
@@ -813,16 +813,16 @@
 kwargs)%0A
+
 %0A       
@@ -1249,68 +1249,8 @@
 ():%0A
-            print(' ***** applying %22%25s%22 on %22%25s%22' %25 (v, ns))%0A
     
@@ -1319,68 +1319,8 @@
 api)
-%0A            print(' ***** ...resulting in %25s' %25 payload%5Bk%5D)
 %0A%0A  
@@ -1726,28 +1726,880 @@
 'id'%5D)%0A%0A        
-return Tru
+if task%5B'state'%5D != 'done':%0A            return False%0A%0A        if 'result_code' in task%5B'result'%5D and %5C%0A                task%5B'result'%5D%5B'result_code'%5D == 0:%0A            # see if there are facts or attrs to apply.%0A            attrlist = task%5B'result'%5D%5B'result_data'%5D.get('attrs', %7B%7D)%0A            factlist = task%5B'result'%5D%5B'result_data'%5D.get('facts', %7B%7D)%0A%0A            for attr, value in attrlist.iteritems():%0A                api._model_create('attrs',%7B'node_id': node_id,%0A                                           'key': attr,%0A                                           'value': value%7D)%0A%0A            for fact, value in factlist.iteritems():%0A                api._model_create('facts',%7B'node_id': node_id,%0A                                           'key': fact,%0A                                           'value': value%7D)%0A%0A            return True%0A%0A        return Fals
 e%0A

add fact/attr publishing