from django import forms

from passerelle.forms import GenericConnectorForm

from .models import Pastell

class PastellForm(GenericConnectorForm):
    class Meta:
        model = Pastell
        exclude = ('slug', 'users', 'document_type', 'document_fields')


class PastellTypeForm(forms.ModelForm):
    class Meta:
        model = Pastell
        fields = ('document_type',)

    def __init__(self, *args, **kwargs):
        super(PastellTypeForm, self).__init__(*args, **kwargs)
        choices = self.instance.get_document_type_choices()
        self.fields['document_type'].choices = choices
        self.fields['document_type'].widget = forms.Select(choices=choices)


    def save(self, commit=True):
        return super(PastellTypeForm, self).save(commit=commit)


class PastellFieldsForm(forms.ModelForm):
    class Meta:
        model = Pastell
        fields = ()

    def __init__(self, *args, **kwargs):
        super(PastellFieldsForm, self).__init__(*args, **kwargs)
        fields = self.instance.get_document_fields()
        initial_data = self.instance.document_fields or {}
        for field_id, field_data in fields.items():
            if field_data.get('no-show') == '1':
                continue
            if field_data.get('name') is None:
                continue
            if field_data.get('type') in ('password', 'file'):
                continue
            self.fields[field_id] = forms.CharField(
                    label=field_data.get('name'),
                    required=field_data.get('requis') == '1',
                    initial=initial_data.get(field_id),
                    )
            if field_data.get('type') == 'textarea':
                self.fields[field_id].widget = forms.Textarea()


    def save(self, commit=True):
        self.instance.document_fields = self.cleaned_data
        return super(PastellFieldsForm, self).save(commit=commit)
