# Create your views here.
from models import Credential
from django.http import HttpResponse, HttpResponseRedirect
import datetime
import uuid
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext

def index( request ):
    return render_to_response('account_index.html', context_instance=RequestContext(request) )
index = login_required(index)

def auth( request ):
    service = request.GET['service']
    # create credential
    ## generat token
    token = str( uuid.uuid4() )
    ## save in db
    cred = Credential( service=service, token=token, user=request.user )
    cred.save()
    # redirect
    ## by service...
    if service == "blogs":
        return callbacks.blogs_callback( cred )
    return HttpResponse("cred=%s" % cred.token)
auth = login_required(auth)


def check_credential( request ):
    cred = request.GET['cred']
    service = request.GET['service']
    # retreive credential in db
    try:
        cred = Credential.objects.get(token=cred, service=service)
        ## if not to old, accept
        if cred.date.today() - cred.date < datetime.timedelta( minutes=10 ):
            response = HttpResponse("VALID")
            response['username'] = cred.user.username
            response['fullname'] = cred.user.get_full_name()
            response['email'] = cred.user.email
            return response
        return HttpResponse("INVALID") 
    except Credential.DoesNotExist:
        return HttpResponse("INVALID") 
    ## else, or if not exist reject

    
class callbacks:
    def blogs_callback( cred ):
        url="http://blogtest.crans.org/actions/auth/return?cred=" + cred.token
        return HttpResponseRedirect(url)
    blogs_callback = staticmethod(blogs_callback)