from django.core.management.commands.runserver import Command as RunserverCommand
from django.core.servers.basehttp import WSGIServer, WSGIRequestHandler
import sys
import threading
from threading import Event
from django.conf import settings

def run(addr, port, wsgi_handler, keep_running=None, ready_event=None):
    server_address = (addr, port)
    httpd = WSGIServer(server_address, WSGIRequestHandler)
    httpd.set_app(wsgi_handler)
    if keep_running is None:
        if ready_event is not None:
            ready_event.set()
        httpd.serve_forever()
    else:
        if ready_event is not None:
            ready_event.set()
        while keep_running():
            httpd.handle_request() 
            


class Command(RunserverCommand):
    def handle(self, addrport='', keep_running=None, ready_event=None, *args, **options):
        import django
        from django.core.servers.basehttp import AdminMediaHandler, WSGIServerException
        from django.core.handlers.wsgi import WSGIHandler
        if args:
            raise CommandError('Usage is testrunserver %s' % self.args)
        if not addrport:
            addr = ''
            port = '8000'
        else:
            try:
                addr, port = addrport.split(':')
            except ValueError:
                addr, port = '', addrport
        if not addr:
            addr = '127.0.0.1'

        if not port.isdigit():
            raise CommandError("%r is not a valid port number." % port)

        admin_media_path = options.get('admin_media_path', '')
        shutdown_message = options.get('shutdown_message', '')
        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'

        from django.conf import settings
        from django.utils import translation
        print "Validating models..."
        self.validate(display_num_errors=True)
        print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
        print "Development server is running at http://%s:%s/" % (addr, port)
        print "Quit the server with %s." % quit_command

        translation.activate(settings.LANGUAGE_CODE)

        try:
            handler = AdminMediaHandler(WSGIHandler(), admin_media_path)
            run(addr, int(port), handler, keep_running, ready_event)
        except WSGIServerException, e:
            # Use helpful error messages instead of ugly tracebacks.
            ERRORS = {
                13: "You don't have permission to access that port.",
                98: "That port is already in use.",
                99: "That IP address can't be assigned-to.",
            }
            try:
                error_text = ERRORS[e.args[0].args[0]]
            except (AttributeError, KeyError):
                error_text = str(e)
            sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n')
            # Need to use an OS exit because sys.exit doesn't work in a thread
        except KeyboardInterrupt:
            if shutdown_message:
                print shutdown_message

    