

import os.path
import popen2
import time

from eventlet import api

from mulib import mu
from mulib import eventrouter

import simplejson

from indra import llsd


from os.path import dirname, join
TEST_SCRIPT_PATH = join(
    join(
        dirname(dirname(dirname(dirname(__file__)))),
    'test'), 'test.py')


class TestConsole(eventrouter.Router):
    transforms = os.path.join(os.path.dirname(__file__), 'testconsole.js')
    stylesheet = os.path.join(os.path.dirname(__file__), 'testconsole.css')

    def __init__(self, my_host):
        self.my_host = my_host
        self.child_ = self
        self.replay = []
        eventrouter.Router.__init__(self)

    def event_connect(self, target):
        for event in self.replay:
            target.msg(*event)
        return "testconsole running on %s" % (self.my_host, )

    def clear_replay(self):
        self.replay = []

    def log_and_broadcast(self, action, data):
        self.replay.append((action, data))
        self.broadcast(action, data)

    def replay_target(self, target):
        for action, data in self.replay:
            target.msg(action, data)

    def handle_post(self, req):
        action = req.get_query('post', 'default')
        data = req.read_body()
        #print action, data,
        ct = req.get_header('content-type')
        if ct == 'application/json':
            data = simplejson.loads(data)
        else:
            data = llsd.parse(data)
        meth = getattr(self, 'post_' + action, None)
        if meth is None:
            meth = lambda *args, **kw: self.log_and_broadcast(action, data)
        if isinstance(data, list):
            meth(*data)
        elif isinstance(data, dict):
            meth(**data)
        elif data is None:
            meth()
        else:
            meth(data)
        if ct == 'application/json':
            req.write('null')
        else:
            req.write(mu.xml('<llsd><undef /></llsd>'))

    def post_log_start(self, id, start_time):
        self.clear_replay()
        self.log_and_broadcast('log_start', [id, start_time])

    def _run_cmd(self, switch, value):
        child = popen2.Popen3([
            '/usr/bin/python2.3',
            TEST_SCRIPT_PATH,
            switch, value,
            '-c', 'http://localhost:12040/test/'
            ])
        status = -1
        while status == -1:
            status = child.poll()
            api.sleep()

    def post_run(self, test_name):
        self._run_cmd('-t', test_name)

    def post_run_suite(self, mode):
        self._run_cmd('-m', mode)

