from django.conf import settings
from django.core.management import call_command
from django.test.testcases import TestCase, TransactionTestCase
import django
import threading
import time
import httplib
from ldt.test.client import WebClient, OAuthClient, OAuthWebClient

        
def launch_webserver(addrport='', keep_running = None, ready_event = None):
    call_command('testrunserver',addrport, keep_running, ready_event)

class WebTestCase(TransactionTestCase):
    
#    def __init__(self, clientKlass = None):
#        super(WebTestCase,self).__init__()
#        if clientKlass is not None:
#            self.client = clientKlass(self.client)

    def set_login_url(self, value):
        self.client.login_url = value
    
    def _pre_setup(self):
        super(WebTestCase,self)._pre_setup()
        self._keep_webserver = True
        self._lock = threading.Lock()
        self._ready_event = threading.Event()
        
        self.baseurl = "http://"+settings.TEST_WEBSERVER_ADDRPORT
        self.client = WebClient()
        self.client.baseurl = self.baseurl
        login_url = '/' + settings.LOGIN_URL[len(settings.BASE_URL):].lstrip('/')
        self.client.login_url = login_url
        
        def keep_runningserver():
            with self._lock:
                return self._keep_webserver
                    
        def launch_server():
            launch_webserver(settings.TEST_WEBSERVER_ADDRPORT, keep_running=keep_runningserver, ready_event = self._ready_event)
        
        #launch_server()
        self._t = threading.Thread(target=launch_server)
        self._t.start()
        self._ready_event.wait()
        time.sleep(0.1)
        
    
    def _post_teardown(self):
        with self._lock:
            self._keep_webserver = False
        conn = httplib.HTTPConnection(settings.TEST_WEBSERVER_ADDRPORT)
        conn.request("HEAD", "/")
        conn.getresponse()
        self._t.join()
        super(WebTestCase,self)._post_teardown()

class OAuthTestCase(TestCase):
    
    def set_consumer(self, key, secret):
        self.client.set_consumer(key, secret)

    def _pre_setup(self):
        super(OAuthTestCase,self)._pre_setup()
        self.client = OAuthClient()
        
class OAuthWebTestCase(WebTestCase):
    
    def set_consumer(self, key, secret):
        self.client.set_consumer(key, secret)

    def _pre_setup(self):
        super(OAuthWebTestCase,self)._pre_setup()
        self.client = OAuthWebClient()
        self.client.baseurl = self.baseurl
        login_url = '/' + settings.LOGIN_URL[len(settings.BASE_URL):].lstrip('/')
        self.client.login_url = login_url



    