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

@author: ymh
'''

import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.http.request import HttpRequest

from egonomy.auth import clean_egonomy_username, get_http_session


logger = logging.getLogger(__name__)

class EgonomyBackend(object):
    """
    Authenticate against egonomy.
    """

    def authenticate(self, username=None, password=None, **kwargs):

        request_meta = getattr(kwargs.get('request', HttpRequest()), 'META', {})

        logger.debug("Egonomy backend : REMOTE_ADDR : %r - REMOTE_HOST : %r" % (request_meta.get('REMOTE_ADDR',''), request_meta.get('REMOTE_HOST','')))

        if request_meta.get('REMOTE_ADDR', None) and request_meta.get('REMOTE_ADDR', None) == getattr(settings, "EGONOMY_SERVER_IP", ''):
            logger.debug("Egonomy backend : IP is %s - return None" % getattr(settings, "EGONOMY_SERVER_IP", ''))
            return None
        
        User = get_user_model()
        login_url = getattr(settings, "EGONOMY_LOGIN_URL", None)
        
        if not login_url:
            return None
        
        logger.debug("EgonomyBackend.authenticate Calling %s" % login_url)

        res_login = get_http_session().post(login_url, data={'user_name': username, 'user_password': password, 'login':'true'})
        
        logger.debug("EgonomyBackend.authenticate Response received %s" % res_login.text)
        
        try:
            res_json = res_login.json()
        except:
            return None
        
        if res_json.get("success", False):
            username = clean_egonomy_username(username, False)
            user, _ = User.objects.get_or_create(**{
                User.USERNAME_FIELD: username
            })
            return user
        return None

    def get_user(self, user_id):
        User = get_user_model()
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None