import floppyforms as forms
from django.contrib.contenttypes.models import ContentType
from crispy_forms.helper import FormHelper
from django.forms.models import inlineformset_factory
from django.contrib.contenttypes.generic import generic_inlineformset_factory

def itf_inlineformset_factory(model, *args, **kwargs):
    title = kwargs.pop('title', '')
    help_text = kwargs.pop('help_text', '')
    is_generic = kwargs.pop('is_generic', False)
    kwargs['extra'] = 1
    #kwargs.delete("title")
    if is_generic:
        FormSet = generic_inlineformset_factory(model, *args, **kwargs)
    else:
        FormSet = inlineformset_factory(model, *args, **kwargs)   
    FormSet.title = title
    FormSet.help_text = help_text
    return FormSet


class ItfForm(forms.ModelForm):
    '''
        All Itf Forms inherit from this
    '''
    inlines = []

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_show_errors = True
        super(ItfForm, self).__init__(*args, **kwargs)



class PopupForm(ItfForm):
    '''
        All popup forms inherit from this
    '''
    pass

class AutocompleteAddWidget(forms.Select):
    '''
    Widget for select2 single select
    Accepts model_class as an additional keyword argument
    model_class should be the model class that this is an add / autocomplete widget for
    '''
    template_name = 'formwidgets/select2.html'
   
    def __init__(self, *args, **kwargs):
        model_class = kwargs.pop('model_class')
        self.ctype = ContentType.objects.get_for_model(model_class)
        if kwargs.has_key('has_add_btn'):
            self.has_add = kwargs.pop('has_add_btn')
        else:
            self.has_add = True

        #self.ctype = ctype
        super(AutocompleteAddWidget, self).__init__(*args, **kwargs)

    def get_context(self, name, value, attrs, *args, **kwargs):
       
        def get_matched_choice_title(choices, id):
            for choice in choices:
                if choice[0] != '' and int(choice[0]) == int(id):
                    return choice[1]
            return ''
                
        #import pdb
        #pdb.set_trace()
        ctx = super(AutocompleteAddWidget, self).get_context(name, value, attrs)
        if value:
            #import pdb
            #pdb.set_trace()
            ctx['title'] = get_matched_choice_title(self.choices, value)
        ctx['ctype'] = self.ctype
        ctx['has_add'] = self.has_add
        return ctx

