#!/usr/bin/env python
"""
This holds Forms and Widgets 

"""
from django import forms
from models import Image, Tag, Size

def imageFormFieldsCB(f, **kwargs):
    if f.name == 'id':
        return f.formfield(widget=forms.widgets.HiddenInput, **kwargs)
    if f.name == 'tags':
        return f.formfield(queryset=Tag.objects.all(), **kwargs)
    else:
        return f.formfield(**kwargs)

BaseImageForm = forms.models.modelform_factory(Image, formfield_callback=imageFormFieldsCB)

class ImageForm(BaseImageForm):
    """This is for editing a form's details - description etc.
    Used by the overridden admin
    """
    width = forms.IntegerField(widget=forms.widgets.HiddenInput)
    height = forms.IntegerField(widget=forms.widgets.HiddenInput)
    format = forms.CharField(widget=forms.widgets.HiddenInput)

    def __init__(self, data, *args, **kwargs):
        super(ImageForm, self).__init__(data, *args, **kwargs)
        try:
            sizes = Size.matching(data['width'], data['height'], data['format'])
            assert len(sizes), 'No size matches image properties.'
        except KeyError, e:
            raise
        else:
            self.fields['size'].queryset = sizes

class ImageUploadForm(forms.Form):
    image = forms.FileField()
