from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponseNotFound
from couponcn.middleware.threadinglocal import tl
import django

def _reverse(*args, **kwargs):
    url = reverse(*args, **kwargs)
    subdomain, path = url.split(':', 1)
    protocol = tl.request.is_secure() and 'https://' or 'http://'
    return '%s%s%s/%s' % (protocol, subdomain[1:], settings.BASE_DOMAIN, path)
django.core.urlresolvers.reverse = _reverse

class SubdomainMiddleware(object):
    def process_request(self, request):
        subdomain = request.get_host().split(settings.BASE_DOMAIN, 1)
        if len(subdomain)  < 2 or subdomain[0] == '':
            return HttpResponseNotFound()
        request.path_info = '/%s:%s' % (subdomain[0], request.path_info)


from threading import local
tl = local()
class ThreadingLocalMiddleware(object):
    def process_request(self, request):
        tl.request = request