import facebook.djangofb as facebook 
from django.contrib.auth.models import User
from django.conf import settings
from utils.utils import set_trace
from django.core.cache import cache

class FacebookBackend:
    def authenticate(self, facebook_request):
        if getattr(facebook_request, 'facebook', None) is None:
            self.add_fb_instance(facebook_request)
        fb = facebook_request.facebook
        django_user = None
        if fb.check_session(facebook_request):
            facebook_id = fb.uid
            query = "SELECT uid, first_name, last_name FROM user WHERE uid=%s" % facebook_id
            result = fb.fql.query(query)[0]
            django_user, created = User.objects.get_or_create(username = result['uid'])
            if created or not django_user.first_name or not django_user.last_name:
                cache.delete('USER_COUNT')
                django_user.email = '%s_%s@facebook' % (result['first_name'], result['last_name'])
                django_user.first_name = result['first_name']
                django_user.last_name = result['last_name']                
                django_user.save()
                
        return django_user
    
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

    def supports_anonymous_user():
        return False

    def supports_object_permissions():
        return False

    @classmethod         
    def add_fb_instance(self, request):
        # if already has a facebook instance, immediately return
        if getattr(request, 'facebook', None) is not None:
            return request
        # auth_token is other important possible param
        api_key = settings.FACEBOOK_API_KEY
        secret_key = settings.FACEBOOK_SECRET_KEY
        app_name = getattr(settings, 'FACEBOOK_APP_NAME', None)
        callback_path = getattr(settings, 'FACEBOOK_CALLBACK_PATH', None)
        internal = getattr(settings, 'FACEBOOK_INTERNAL', True)
        request.facebook = facebook.Facebook(
            api_key=api_key,
            secret_key=secret_key,
            app_name=app_name,
            callback_path=callback_path,
            internal=internal)
