import time
import socket
import helpers
import SocketServer
import subprocess
import os
import unittest


class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    dispatcher_server = None  # Holds the dispatcher server host/post information
    last_communication = None  # keeps track of last communication from dispatcher
    busy = False  # status flag
    dead = False  # status flag


def dispatcher_checker(server):

    while not server.dead:
        time.sleep(5)
        if (time.time() - server.last_communication) > 10:
            try:
                response = helpers.communicate(server.dispatcher_server["host"],
                                               int(server.dispatcher_server["port"]),
                                               "status")
                if response != "OK":
                    print "Dispatcher is no longer functional"
                    server.shutdown()
                    return
            except socket.error as e:
                print "Can't communicate with dispatcher: %s" % e
                server.shutdown()
                return


class TestHandler(SocketServer.BaseRequestHandler):

    """..."""

    def handle(self):

        """..."""
        if command == "ping":
            print "pinged"
            self.server.last_communication = time.time()
            self.request.sendall("pong")
        elif command == "runtest":
            print "got runtest command: am I busy? %s" % self.server.busy
            if self.server.busy:
                self.request.sendall("BUSY")
            else:
                self.request.sendall("OK")
                print "running"
                commit_id = command_groups.group(2)[1:]
                self.server.busy = True
                self.run_tests(commit_id, self.server.repo_folder)
                self.server.busy = False

    def run_tests(self, commit_id, repo_folder):
        # update repo
        output = subprocess.check_output(["./test_runner_script.sh", repo_folder, commit_id])
        print output

        # run the tests
        test_folder = os.path.join(repo_folder, "tests")
        suite = unittest.TestLoader().discover(test_folder)
        result_file = open("results", "w")
        unittest.TextTestRunner(result_file).run(suite)
        result_file.close()
        result_file = open("results", "r")
        # give the dispatcher results
        output = result_file.read()
        helpers.communicate(self.server.dispatcher_server["host"],
                            int(self.server.dispatcher_server["port"]),
                            "results:%s:%s:%s" % (commit_id, len(output), output))
