import datetime

from django.db import models
from django.http import JsonResponse
from django.shortcuts import redirect

from localflavor.us.models import USStateField

from wagtail.wagtailadmin.edit_handlers import (
    FieldPanel,
    MultiFieldPanel,
)
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailembeds import embeds
from wagtail.wagtailembeds.exceptions import EmbedException
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
from wagtail.wagtailsearch import index


DISPATCH_TYPE_VIDEO = 'v'
DISPATCH_TYPE_AUDIO = 'a'
DISPATCH_TYPE_CHOICES = (
    (DISPATCH_TYPE_VIDEO, 'Video'),
    (DISPATCH_TYPE_AUDIO, 'Audio'),
)


class DispatchPage(Page):
    date = models.DateField(default=datetime.date.today)

    city = models.CharField(max_length=255)
    state = USStateField()

    description = RichTextField(blank=True)

    poster_image = models.ForeignKey(
        'localore_admin.LocaloreImage',
        null=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    dispatch_type = models.CharField(
        max_length=1,
        choices=DISPATCH_TYPE_CHOICES,
        default=DISPATCH_TYPE_VIDEO,
    )

    embed_url = models.URLField(
        "Embed URL",
        help_text="YouTube or SoundCloud"
    )

    search_fields = Page.search_fields + (
        index.SearchField('location'),
        index.SearchField('description', partial_match=True),
    )

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        MultiFieldPanel(
            [FieldPanel('city'), FieldPanel('state')],
            "Location"
        ),
        FieldPanel('description', classname="full"),
        ImageChooserPanel('poster_image'),
        FieldPanel('dispatch_type'),
        FieldPanel('embed_url'),
    ]

    parent_page_types = ['dispatches.DispatchesIndexPage']
    subpage_types = []

    @property
    def dispatches_index(self):
        return self.get_ancestors().type(DispatchesIndexPage).last()

    def serve(self, request):
        do_json = 'json' in request.GET
        if do_json:
            response = {}

            response['title'] = self.title

            prev_page = self.get_prev_siblings().live().first()
            response['prev_url'] = prev_page.url + '?json' if prev_page else None

            next_page = self.get_next_siblings().live().first()
            response['next_url'] = next_page.url + '?json' if next_page else None

            response['embed_url'] = self.embed_url

            try:
                response['embed_html'] = embeds.get_embed(self.embed_url).html
            except EmbedException:
                response['embed_html'] = ''

            return JsonResponse(response)
        else:
            index_url = self.dispatches_index.url + '?dispatch=' + self.url
            return redirect(index_url, permanent=False)


class DispatchesIndexPage(Page):
    subtitle = models.CharField(max_length=255, blank=True)
    intro = RichTextField(blank=True)

    default_dispatch_type = models.CharField(
        max_length=1,
        choices=DISPATCH_TYPE_CHOICES,
        default=DISPATCH_TYPE_VIDEO,
    )

    content_panels = Page.content_panels + [
        FieldPanel('subtitle', classname="full"),
        FieldPanel('intro', classname="full"),
        FieldPanel('default_dispatch_type'),
    ]

    subpage_types = ['dispatches.DispatchPage']

    @property
    def dispatches(self):
        return (
            DispatchPage.objects.live().descendant_of(self).order_by('-date')
        )

    def get_context(self, request):
        dispatches = self.dispatches

        dispatches = dispatches.filter(
            dispatch_type=request.GET.get('t', self.default_dispatch_type)
        )

        context = super(DispatchesIndexPage, self).get_context(request)
        context['dispatches'] = dispatches

        return context

@@ -2074,17 +2074,10 @@
     
-do_json =
+if
  'js
@@ -2098,27 +2098,8 @@
 .GET
-%0A        if do_json
 :%0A  
@@ -2112,20 +2112,16 @@
     resp
-onse
  = %7B%7D%0A%0A 
@@ -2135,20 +2135,16 @@
     resp
-onse
 %5B'title'
@@ -2187,39 +2187,249 @@
 e = 
-self.get_prev_siblings().live()
+(%0A                DispatchPage.objects.live()%0A                .sibling_of(self, False)%0A                .filter(path__lte=self.path)%0A                .order_by('-path')%0A                .filter(dispatch_type=self.dispatch_type)%0A                
 .fir
@@ -2445,24 +2445,34 @@
         
+)%0A            
 resp
-onse
 %5B'prev_u
@@ -2554,39 +2554,248 @@
 e = 
-self.get_next_siblings().live()
+(%0A                DispatchPage.objects.live()%0A                .sibling_of(self, False)%0A                .filter(path__gte=self.path)%0A                .order_by('path')%0A                .filter(dispatch_type=self.dispatch_type)%0A                
 .fir
@@ -2811,24 +2811,34 @@
         
+)%0A            
 resp
-onse
 %5B'next_u
@@ -2900,36 +2900,32 @@
             resp
-onse
 %5B'embed_url'%5D = 
@@ -2969,36 +2969,32 @@
             resp
-onse
 %5B'embed_html'%5D =
@@ -3087,20 +3087,16 @@
     resp
-onse
 %5B'embed_
@@ -3144,20 +3144,16 @@
 nse(resp
-onse
 )%0A      
@@ -3160,16 +3160,17 @@
   else:%0A
+%0A
         
@@ -3963,24 +3963,131 @@
 %0A        )%0A%0A
+    def get_dispatch_type(self, request):%0A        return request.GET.get('t', self.default_dispatch_type)%0A%0A
     def get_
@@ -4218,40 +4218,15 @@
 ype=
-request.GET.get('t', self.defaul
+self.ge
 t_di
@@ -4228,32 +4228,40 @@
 et_dispatch_type
+(request
 )%0A        )%0A%0A   

Fix prev/next URLs to work with dispatch types.