from django.contrib.auth import authenticate
from django import forms
from django.utils.translation import ugettext_lazy as _

class AuthenticationForm(forms.Form):
    
    username = forms.CharField(label=_("Username"), max_length=30)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

    def __init__(self, request=None, *args, **kwargs):
        
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(_("Podaj poprawny login i haslo."))
            elif not self.user_cache.is_active:
                raise forms.ValidationError(_("Konto tego uzytkownika jest nieaktywne."))
        self.check_for_test_cookie()
        return self.cleaned_data

    def check_for_test_cookie(self):
        if self.request and not self.request.session.test_cookie_worked():
            raise forms.ValidationError(
                _("Twoja przegladarka ma wylaczona oblsuge ciasteczek. "
                  "Ciasteczka sa wymagane do logowania."))

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache
        
