from blog.models import Entry, Blogmark, Quotation
from baseconv import base62
from django.http import HttpResponsePermanentRedirect, Http404
from django.shortcuts import get_object_or_404

BASE_URL = 'http://simonwillison.net'
SHORT_BASE_URL = 'http://swtiny.eu/'
PREFIXES = {
    'E': Entry,
    'B': Blogmark,
    'Q': Quotation,
}

def redirect_view(request, tiny):
    "This should be hooked up to /shorten/(.*) in the URLconf"
    if not tiny:
        return HttpResponsePermanentRedirect(BASE_URL + '/')
    prefix = tiny[0]
    tiny = tiny[1:]
    try:
       model = PREFIXES[prefix] 
       id = base62.to_decimal(tiny)
    except (ValueError, KeyError):
       raise Http404
    obj = get_object_or_404(model, pk = id)
    url = obj.get_absolute_url()
    if not url.startswith('http://') and not url.startswith('https://'):
        url = BASE_URL + url
    return HttpResponsePermanentRedirect(url)

def shorten(obj):
    "Returns a shorter URL for a Django model object, or None if not available"
    found = None
    for prefix, model in PREFIXES.items():
        if model._meta.db_table == obj._meta.db_table:
            found = prefix
    if not found:
        return None
    return SHORT_BASE_URL + found + base62.from_decimal(obj.id)

