# -*- coding: utf-8 -*-
'''
Created on 2010/04/25

@author: katsuhiro Inagaki
'''
from datetime import datetime

from django.conf import settings
from django.contrib.auth import authenticate, views as djangoview, REDIRECT_FIELD_NAME
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render_to_response
from django.views.generic.simple import redirect_to
from django.utils.translation import ugettext_lazy as _

from djanction.appauth.models import User, LoginLog


def login(request, template_name='appauth/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    redirect_page = request.REQUEST.get(redirect_field_name, '')
    if len(redirect_page) == 0:
        redirect_page = settings.LOGIN_REDIRECT_URL

    if request.method == 'GET':
        return djangoview.login(request, template_name)
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                from django.contrib.auth import login
                login(request, user)
                _set_session_expire(request)
                _log_login(request, True)

                return redirect_to(
                    request, redirect_page,
                )
            else:
                _log_login(request, False)
                return _direct_to_login(request, _('The account is stopping.'))
        else:
            _log_login(request, False)
            return _direct_to_login(request, _('Invalid user id or password.'))


def index(request):
    return _direct_to_login(request)


def _direct_to_login(request, msg=None):
    form = AuthenticationForm(request.POST)
    return render_to_response('appauth/login.html',{
        'form': form,
        'msg': msg,
    })


def _set_session_expire(request):
    if hasattr(settings, 'SESSION_EXPIRE_TIME'):
        session_expire = settings.SESSION_EXPIRE_TIME
    else:
        session_expire = 1800
    request.session.set_expiry(session_expire)


def _log_login(request, isSuccess):
    username = request.POST['username']
    from django.core.exceptions import ObjectDoesNotExist
    try:
        user = User.objects.get(username=username)
    except ObjectDoesNotExist:
        return
    log = LoginLog()
    log.user = user
    log.is_success = isSuccess
    log.session_id = request.COOKIES['sessionid']
    log.ip_address = request.META['REMOTE_ADDR']
    log.user_agent = request.META['HTTP_USER_AGENT']
    log.login_date = datetime.today()
    log.save()
