"""Django Forms to administrate the event content on the frontend."""
from django import forms
from django.contrib.auth import get_user_model
from django.utils.translation import gettext as _

from . import models


class ClearableMultipleFileInput(forms.widgets.ClearableFileInput):
    allow_multiple_selected = True
    accept = "image/jpg"


class MultipleFileField(forms.FileField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault("widget", ClearableMultipleFileInput())
        super().__init__(*args, **kwargs)

    def clean(self, data, initial=None):
        single_file_clean = super().clean
        if isinstance(data, (list, tuple)):
            result = [single_file_clean(d, initial) for d in data]
        else:
            result = single_file_clean(data, initial)
        return result


class PhotoUploadForm(forms.Form):
    """Form to upload multiple photos to a single event.
    TODO: Check multiple upload
    """
    error_css_class = 'error'
    required_css_class = 'required'
    photographer = forms.ModelChoiceField(get_user_model().objects.all(),
                                          required=True, )
    event = forms.ModelChoiceField(models.Event.objects.all(), required=True, )
    upload = MultipleFileField(
        label=_('Images'),
        required=True,
    )


class EditPhotoForm(forms.ModelForm):
    """From to edit the metadata of a photo."""
    error_css_class = 'error'
    required_css_class = 'required'

    class Meta(object):
        """Metadata to localize and customize the ModelForm."""
        model = models.Photo
        fields = ('event', 'name', 'description', 'photographer',
                  'created_date', 'on_startpage')


class EventForm(forms.ModelForm):
    """Form to add or edit an event."""
    error_css_class = 'error'
    required_css_class = 'required'

    start = forms.SplitDateTimeField(
        label=_('start'), required=True,
    )
    end = forms.SplitDateTimeField(
        label=_('end'), required=False,
    )

    class Meta(object):
        """Metadata to localize and customize the ModelForm."""
        model = models.Event
        exclude = ('event_count', 'event_series',)


EventSeriesFormset = forms.inlineformset_factory(  # Ignore PyLintBear (C0103)
    models.Event,
    models.Event,
    fields=('start', 'end'),
    form=EventForm)
