# -*- 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 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):

        
        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