# -*- coding: utf-8 -*-
'''
Created on Aug 4, 2013

@author: ymh
'''
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import (UserChangeForm as AuthUserChangeForm, 
    UserCreationForm as AuthUserCreationForm)
from django.core.exceptions import ValidationError
from django.forms import Form
from django.forms.fields import ChoiceField, CharField
from django.utils.translation import ugettext as _
from .models import Record


User = get_user_model()

class UserCreationform(AuthUserCreationForm):
    class Meta:
        model = User
        
    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise ValidationError(self.error_messages['duplicate_username'])    
    

class UserChangeForm(AuthUserChangeForm):
    language = ChoiceField(label=_("language"), choices=[(k,_(v)) for k,v in settings.LANGUAGES], initial=settings.LANGUAGE_CODE[:2])
    class Meta:
        model = User


class RecordFilterForm(Form):
    title = CharField(required=True, min_length=1)
    def get_filter_qs(self, qs=None):
        if qs is None:
            qs = Record.objects.select_related("language").prefetch_related('titles').distinct()  # @UndefinedVariable
        t = self.cleaned_data.get('title',None)
        if t:
            qs = qs.filter(titles__title__icontains=t)
        return qs

