# -*- coding: utf-8 -*-
'''
Created on Mar 19, 2014

@author: ymh
'''
import logging

from django.conf import settings
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.http.response import HttpResponseBadRequest

from egonomy.auth import clean_egonomy_username, get_http_session


logger = logging.getLogger(__name__) 

class EgonomyUserTokenMiddleware(object):

    parameter = (getattr(settings, "EGONOMY_TOKEN_NAME", None) or "egonomytoken")

    def process_request(self, request):
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Egonomy user token auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the EgonomyUserTokenMiddleware class.")

        logger.debug("EgonomyUserTokenMiddleware called")
        token = request.POST.get(self.parameter,request.GET.get(self.parameter,None))
        if not token:
            return

        logger.debug("EgonomyUserTokenMiddleware token found %s" % token)
        
        token_check_url = getattr(settings, "EGONOMY_TOKEN_CHECK_URL", None)
        if not token_check_url:
            return
        
        res_check = get_http_session().get(token_check_url, params={self.parameter:token})
        logger.debug("EgonomyUserTokenMiddleware json raw %s" % res_check.text)
        res_json = res_check.json()
        
        logger.debug("EgonomyUserTokenMiddleware json %s" % res_json )
        if not res_json.get('success', False):
            return
        
        username = res_json.get('username', None)
        if not username :
            return HttpResponseBadRequest("Empty username")

        #"namespace" username
        username = clean_egonomy_username(username, res_json.get('external', True))
        # If the user is already authenticated and that user is the user we are
        # getting passed in the headers, then the correct user is already
        # persisted in the session and we don't need to continue.
        if request.user.is_authenticated() and request.user.get_username() == username:
                return
        else:
            auth.logout(request)
        
        # create user if not known
        # login user
        UserModel = get_user_model()

        # Note that this could be accomplished in one try-except clause, but
        # instead we use get_or_create when creating unknown users since it has
        # built-in safeguards for multiple threads.
        user, _ = UserModel.objects.get_or_create(**{
                UserModel.USERNAME_FIELD: username
        })
        
        if user:
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            # User is valid.  Set request.user and persist user in the session
            # by logging the user in.
            request.user = user
            
            auth.login(request, user)
