import random
from django.http import HttpResponseRedirect
from django.conf import settings

extensions = (
    ".do",
    ".pl",
    ".py",
    ".asp",
    ".cfm",
    ".cgi",
    ".dll",
    ".htm",
    ".jsp",
    ".xml",
    ".exe",
    ".php",
    ".aspx",
    ".html",
    ".php3",
    ".php4",
    ".shtml",
    ".action",
)

indexes = (
    "/index",
    "/main",
)

class RandomFileExtensionMiddleware(object):
    """
    A middleware that replaces the request path automatically with a random
    file extension to make you feel nostalgic for old crufty URLs. This
    will respect settings.APPEND_SLASH when it converts the request path back
    to normal.
    """
    def _is_valid_extension(self, path):
        for i, ext in enumerate(extensions):
            if path.endswith(ext):
                return True
        return False
    
    def _is_valid_index(self, path):
        for i, index in enumerate(indexes):
            if path.startswith(index):
                return True
        return False
    
    def process_request(self, request):
        if request.path == "/":
            request.path = random.choice(indexes) + random.choice(extensions)
            return HttpResponseRedirect(request.build_absolute_uri())

        elif request.path.endswith("/"):
            request.path = request.path[:-1] + random.choice(extensions)
            return HttpResponseRedirect(request.build_absolute_uri())

        elif self._is_valid_extension(request.path):
            if self._is_valid_index(request.path):
                request.path = "/"
            else:
                path = request.path.split("/")
                path[-1] = "".join(path[-1].split(".")[:-1])
                if settings.APPEND_SLASH:
                    path[-1] = path[-1] + '/'
                request.path = "/".join(path)