import base64
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.views.generic.simple import direct_to_template
from django.conf import settings
from google.appengine.api.images import Image
from google.appengine.api import users
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt  #TODO - fix this
from utils.utils import set_trace
import simplejson
import logging
import facebook.djangofb as facebook
from facebook_backend import FacebookBackend

def res(request, title):
    return render_to_response("login/check_django_login.html", { 
            'user': request.user,
            'title': title,
            'django_user': request.user, 
            'gae_user': users.get_current_user(), 
            'verify': reverse('openid_verify'),
            'login_url': reverse('openid_main_login'),
            'logout_url': users.create_logout_url(reverse('openid_logout')) })


def create_account(request):
    username = request.POST['username']
    password = request.POST['password']
    user, created = User.objects.get_or_create(username=username)
    if not created:
        return HttpResponseRedirect('openid_main_login')
    user.set_password(password)
    user.save()
    user = authenticate(username=username, password=password)
    login(request, user)
    return HttpResponseRedirect(reverse('openid_verify'))

@csrf_exempt
def django_login(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('openid_verify'))
        else:
            # Return a 'disabled account' error message
            return HttpResponseRedirect(reverse('openid_main_login'))
    else:
        # Return an 'invalid login' error message.
        return HttpResponseRedirect(reverse('openid_main_login'))


@csrf_exempt
def do_facebook_login(request):
    django_user = authenticate(facebook_request = request)
    if django_user:
        login(request, django_user)
        if 'next_url' in request.GET:
            org_url = request.GET.get('next_url')
            next = base64.urlsafe_b64decode(str(org_url))
        else:
            next = reverse('content')
        return HttpResponseRedirect(next)
    #nasty hack to get around facebook login error on first attempt    
    if 'installed' in request.GET and 'next_url' in request.GET:
        if getattr(request, 'facebook', None) is None: 
            FacebookBackend.add_fb_instance(request)   
        fb = request.facebook                     
        org_url = request.GET.get('next_url')
        next = base64.urlsafe_b64decode(str(org_url))
        next_url = '%s?next_url=%s' % (reverse('do_facebook_login'), base64.urlsafe_b64encode(next))
        next_url = request.build_absolute_uri(next_url)    
        login_url = fb.get_login_url(next=next_url, canvas=False)
        return HttpResponseRedirect(login_url)
    return HttpResponseRedirect(reverse('home'))
                                                                                     
    
        
@csrf_exempt
def facebook_login(request):
    next_url = '%s?next_url=%s' % (reverse('do_facebook_login'), 
        base64.urlsafe_b64encode(request.REQUEST.get('next_url', reverse('home'))))
    next_url = request.build_absolute_uri(next_url)
    if getattr(request, 'facebook', None) is None:
        FacebookBackend.add_fb_instance(request)        
    fb = request.facebook
    if not fb.check_session(request):
        return HttpResponseRedirect(fb.get_login_url(next=next_url, canvas=False))


@csrf_exempt
def myopenid_login(request):
    username = request.POST['username']
    federated_identity = username + '.myopenid.com'
    next_url = '%s?next_url=%s' % (reverse('openid_login'), 
        base64.urlsafe_b64encode(request.REQUEST.get('next_url', reverse('home'))))
    return HttpResponseRedirect(users.create_login_url(dest_url = next_url, federated_identity = federated_identity))


@csrf_exempt
def google_login(request):
    next_url = '%s?next_url=%s' % (reverse('openid_login'),
        base64.urlsafe_b64encode(request.REQUEST.get('next_url', reverse('home'))))
    logging.debug('next url: %s' % next_url)
    return HttpResponseRedirect(users.create_login_url(dest_url = next_url, federated_identity = 'google.com/accounts/o8/id'))
    
@csrf_exempt
def yahoo_login(request):
    next_url = '%s?next_url=%s' % (reverse('openid_login'), 
        base64.urlsafe_b64encode(request.REQUEST.get('next_url', reverse('home'))))
    logging.debug('next url: %s' % next_url)    
    return HttpResponseRedirect(users.create_login_url(dest_url = next_url, federated_identity = 'http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds'))    


def main_login(request):
    gae_user = users.get_current_user()
    if not gae_user:
        dest = request.GET.get('next', '/')
        return render_to_response('login/login.html', {
            'google_login_url': reverse('openid_google_login'),
            'myopenid_login_url': reverse('openid_myopenid_login'),
            'django_login_url': reverse('openid_django_login'),
            'django_create_account': reverse('openid_create_account') })

    django_user = authenticate(gae_user = gae_user)
    login(request, django_user)
    return res(request, "You're in!")


def do_login(request):
    gae_user = users.get_current_user()
    if gae_user:
        django_user = authenticate(gae_user = gae_user)
        login(request, django_user)
        if 'next_url' in request.GET:
            org_url = request.GET.get('next_url')
            next = base64.urlsafe_b64decode(str(org_url))
        else:
            next = reverse('content')
        return HttpResponseRedirect(next)
    else:
        return HttpResponseRedirect(reverse('home'))


def do_logout(request):
    logout(request) #django logout
    if users.get_current_user(): #we are logged in via open_id
        logout_url = users.create_logout_url(reverse('home')) #openid logout
    else: #must be facebook
        if getattr(request, 'facebook', None) is None:
            FacebookBackend.add_fb_instance(request)  
        fb = request.facebook                    
        logout_url = "http://www.facebook.com/logout.php?api_key=%s&;session_key=%s&next=%s" % (
            settings.FACEBOOK_APP_ID, fb.session_key, request.build_absolute_uri(reverse('home')))
    return HttpResponseRedirect(logout_url)


@login_required
def verify(request):
    return res(request, "You're verified!")
      


def ajax_test(request):
    user = users.get_current_user()
    if user:
        return HttpResponse(simplejson.dumps({ 'result': user.nickname() }))
    else:
        return HttpResponse(simplejson.dumps({ 'result': 'anonymous' }))


def ajax_test_django(request):
    user = request.user
    if user.is_authenticated():
        return HttpResponse(simplejson.dumps({ 'result': user.username }))
    else:
        return HttpResponse(simplejson.dumps({ 'result': 'anonymous' }))
