#encoding=utf-8
'''
Created on 05/03/2009

@author: rgonzalez
'''
import re
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from scheduler.models import Facultad, Carrera

class HorariosModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.__str__()

class RegistrationForm(forms.Form):
    username    = forms.CharField(label='Usuario', max_length=30)
    first_name  = forms.CharField(label='Nombre', max_length=30)
    last_name   = forms.CharField(label='Apellido', max_length=30)
    email       = forms.EmailField(label='Email')
    password1   = forms.CharField(
                    label='Contraseña', widget=forms.PasswordInput()
                    )
    password2   = forms.CharField(
                    label='Confirmar Contraseña', widget=forms.PasswordInput()
                    )
    matricula   = forms.IntegerField(label = 'Matricula')
    facultad    = HorariosModelChoiceField(
                    queryset=Facultad.objects.all() ,label= 'Facultad', empty_label = None)    
    carrera     = HorariosModelChoiceField(
                    queryset=Carrera.objects.filter(facultad = Facultad.objects.all()[0]), label='Carrera')
    
    def clean_password2(self):
        if 'password1' in self.cleaned_data:
            password1 = self.cleaned_data['password1']
            password2 = self.cleaned_data['password2']
            if password1 == password2:
                return password2
        raise forms.ValidationError('Las contraseñas no concuerdan')

    def clean_username(self):
        username = self.cleaned_data['username']
        if not re.search(r'^\w+$', username):
            raise forms.ValidationError('Caracteres no validos en el nombre de usuario')
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError('El nombre de usuario ya existe.')

    def setFacultadToCarrera(self, facultad):
        self.fields['carrera'].queryset = Carrera.objects.filter(facultad = facultad)




SEMESTRE_CHOICES = (
    (1,'1'),
    (2,'2'),
    (3,'3'),
    (4,'4'),
    (5,'5'),
    (6,'6'),
    (7,'7'),
    (8,'8'),
    (9,'9'),
)
class SemestreChoice(forms.Form):
    semestre = forms.ChoiceField(choices = SEMESTRE_CHOICES)
    semestre.widget.attrs["onchange"]= "this.form.submit()"
    