import datetime
import json
from os.path import splitext

from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django import forms
from wagtail.blocks import StructBlock
from wagtail.contrib.forms.forms import FormBuilder
from wagtail.contrib.forms.models import AbstractFormField, FORM_FIELD_CHOICES, AbstractForm
from wagtail.fields import StreamField
from modelcluster.models import ClusterableModel
from wagtail.images import get_image_model
from wagtail.images.fields import WagtailImageField
from wagtail.search.models import Query
from wagtail import blocks
from wagtail.models import Collection
from wagtail.images.models import Image


from wagtail.models import (
    Page,
    Orderable
)
from wagtail.fields import RichTextField
from wagtail.admin.panels import (
    FieldPanel,
    InlinePanel,
    MultiFieldPanel,
)
from modelcluster.fields import ParentalKey, ParentalManyToManyField


class ImageUploadForm(AbstractFormField):
    field_type = models.CharField(
        verbose_name='field type',
        max_length=16,
        choices=list(FORM_FIELD_CHOICES) + [('image', 'Upload Image')]
    )

    page = ParentalKey('WeddingPage', related_name='form_fields', on_delete=models.CASCADE)
class CustomFormBuilder(FormBuilder):

    def create_image_field(self, field, options):
        return WagtailImageField(**options)


class MultipleImage(models.Model):
	images = models.FileField()


class WeddingPage(AbstractForm):
    form_builder = CustomFormBuilder
    template = "home/weddingpage.html"

    uploaded_image_collection = models.ForeignKey(
        'wagtailcore.Collection',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )
    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request)
        images = Image.objects.all().order_by('id').reverse()

        context['images'] = images
        return context


    # content_panels...
    content_panels = Page.content_panels + [
        InlinePanel('form_fields', label="Blogs"),
    ]

    settings_panels = AbstractForm.settings_panels + [
        FieldPanel('uploaded_image_collection')
    ]


    def get_uploaded_image_collection(self):
        """
        Returns a Wagtail Collection, using this form's saved value if present,
        otherwise returns the 'Root' Collection.
        """
        collection = self.uploaded_image_collection
        return collection or Collection.get_first_root_node()

    @staticmethod
    def get_image_title(filename):
        """
        Generates a usable title from the filename of an image upload.
        Note: The filename will be provided as a 'path/to/file.jpg'
        """

        if filename:
            result = splitext(filename)[0]
            result = result.replace('-', ' ').replace('_', ' ')
            return result.title()
        return ''


    def process_form_submission(self, form):
        """
        Processes the form submission, if an Image upload is found, pull out the
        files data, create an actual Wgtail Image and reference its ID only in the
        stored form response.
        """

        cleaned_data = form.cleaned_data

        for name, field in form.fields.items():
            if isinstance(field, WagtailImageField):
                image_files_data = cleaned_data[name]
                if image_file_data:
                    for image_file_data in image_files_data:
                        ImageModel = get_image_model()

                        kwargs = {
                            'file': cleaned_data[name],
                            'title': self.get_image_title(cleaned_data[name].name),
                            'collection': self.get_uploaded_image_collection(),
                        }

                        if form.user and not form.user.is_anonymous:
                            kwargs['uploaded_by_user'] = form.user

                        image = ImageModel(**kwargs)
                        image.save()
                        # saving the image id
                        # alternatively we can store a path to the image via image.get_rendition
                        cleaned_data.update({name: image.pk})
                else:
                    # remove the value from the data
                    del cleaned_data[name]

        submission = self.get_submission_class().objects.create(
            form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),
            # note: Wagtail 3.0 & beyond will no longer need to wrap this in json.dumps as it uses Django's JSONField under the hood now - https://docs.wagtail.org/en>
            page=self,
        )

        # important: if extending AbstractEmailForm, email logic must be re-added here
        # if self.to_address:
        #    self.send_mail(form)

        return submission
