from django import forms
from django.contrib.auth.models import User
from rango.models import Page, Category, UserProfile
from django.contrib.auth import authenticate, login

class CategoryForm(forms.ModelForm):

    name=forms.CharField(max_length=128, help_text="Please enter the category name.")
    views=forms.IntegerField(widget=forms.HiddenInput(),initial=0,)
    likes=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
    slug=forms.CharField(widget=forms.HiddenInput(),required=False)

    class Meta:
        model = Category
        fields = ('name',)

class PageForm(forms.ModelForm):
    title=forms.CharField(max_length=128, help_text="Please enter the title of the page.")
    url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
    views=forms.IntegerField(widget=forms.HiddenInput(), initial=0)

    class Meta:
        model=Page
        exclude=('category',)
        
    def clean(self):
        cleaned_data = self.cleaned_data 
        url = cleaned_data.get('url')
        if url and not url.startswith('http://'):
            url = 'http://' + url
            cleaned_data['url'] = url
        return cleaned_data

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = User
        fields = ('username', 'email', 'password')

class LoginForm(forms.Form):
    username = forms.CharField(max_length=255, required=True)
    password = forms.CharField(widget=forms.PasswordInput, required=True)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        if not user or not user.is_active:
            raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
        return self.cleaned_data

    def login(self, request):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        return user

class UserProfileForm(forms.ModelForm): 
    website = forms.URLField(required=False) 
    picture = forms.ImageField(required=False)
    class Meta:
        model = UserProfile 
        exclude = ('user',)