# Path: puput/models.py
# class EntryPage(Entry, Page):
#     # Search
#     search_fields = Page.search_fields + [
#         index.SearchField('body'),
#         index.SearchField('excerpt'),
#         index.FilterField('page_ptr_id')
#     ]
# 
#     # Panels
#     content_panels = getattr(Entry, 'content_panels', [])
# 
#     promote_panels = Page.promote_panels + getattr(Entry, 'promote_panels', [])
# 
#     settings_panels = Page.settings_panels + [
#         FieldPanel('date'), FieldPanel('owner'),
#     ] + getattr(Entry, 'settings_panels', [])
# 
#     # Parent and child settings
#     parent_page_types = ['puput.BlogPage']
#     subpage_types = []
# 
#     def get_sitemap_urls(self, request=None):
#         from .urls import get_entry_url
#         root_url = self.get_url_parts()[1]
#         entry_url = get_entry_url(self, self.blog_page.page_ptr, root_url)
#         return [
#             {
#                 'location': root_url + entry_url,
#                 # fall back on latest_revision_created_at if last_published_at is null
#                 # (for backwards compatibility from before last_published_at was added)
#                 'lastmod': (self.last_published_at or self.latest_revision_created_at),
#             }
#         ]
# 
#     @property
#     def blog_page(self):
#         return self.get_parent().specific
# 
#     @property
#     def related(self):
#         return [related.entrypage_to for related in self.related_entrypage_from.all()]
# 
#     @property
#     def has_related(self):
#         return self.related_entrypage_from.count() > 0
# 
#     def get_absolute_url(self):
#         return self.full_url
# 
#     def get_context(self, request, *args, **kwargs):
#         context = super(EntryPage, self).get_context(request, *args, **kwargs)
#         context['blog_page'] = self.blog_page
#         return context
# 
#     class Meta:
#         verbose_name = _('Entry')
#         verbose_name_plural = _('Entries')
# 
# Path: puput/utils.py
# def strip_prefix_and_ending_slash(path):
#     """
#     If puput and wagtail are registered with a prefix, it needs to be removed
#     so the 'entry_page_serve_slug' or 'blog_page_feed_slug' resolutions can work.
#     Ex, here with a dynamic (i18n_patterns()) + a static prefix :
#     urlpatterns += i18n_patterns(
#         url(r'^blah/', include('puput.urls')),
#         url(r'^blah/', include(wagtail_urls)),
#     )
#     The prefix is simply the root where Wagtail page are served.
#     https://github.com/torchbox/wagtail/blob/stable/1.8.x/wagtail/wagtailcore/urls.py#L36
#     """
#     return path.replace(reverse('wagtail_serve', args=[""]), '', 1).rstrip("/")
# 
# def import_model(path_or_callable):
#     if hasattr(path_or_callable, '__call__'):
#         return path_or_callable
#     else:
#         assert isinstance(path_or_callable, str)
#         package, attr = path_or_callable.rsplit('.', 1)
#         return getattr(import_module(package), attr)


from django.conf import settings
from django.http import Http404, HttpResponse
from django.views.generic import View
from django.views.decorators.csrf import ensure_csrf_cookie
from django.utils.decorators import method_decorator
from wagtail.core import hooks
from wagtail.core.models import Site
from .models import EntryPage
from .utils import strip_prefix_and_ending_slash, import_model
            # Example:
            # splited_path =  ['es', 'blog', '2016', '06', '23', 'blog-entry']
            # slicing this way you obtain:
            # path_components =  ['es', 'blog', 'blog-entry']
            # with the oldest solution you'll get ['es', 'blog-entry']
            # and a 404 will be raised
            splited_path = strip_prefix_and_ending_slash(request.path).split("/")
            path_components = splited_path[:-4] + splited_path[-1:]
        else:
            path_components = [strip_prefix_and_ending_slash(request.path).split('/')[-1]]
        page, args, kwargs = site.root_page.specific.route(request, path_components)

        for fn in hooks.get_hooks('before_serve_page'):
            result = fn(page, request, args, kwargs)
            if isinstance(result, HttpResponse):
                return result
        return page.serve(request, *args, **kwargs)


class EntryPageUpdateCommentsView(View):

    def post(self, request, entry_page_id, *args, **kwargs):
        try:
            entry_page = EntryPage.objects.get(pk=entry_page_id)
            blog_page = entry_page.blog_page
            comment_class = import_model(settings.PUPUT_COMMENTS_PROVIDER)(blog_page, entry_page)
            num_comments = comment_class.get_num_comments()
            entry_page.num_comments = num_comments
            entry_page.save(update_fields=('num_comments',))
            return HttpResponse()

# Path: puput/models.py
# class EntryPage(Entry, Page):
#     # Search
#     search_fields = Page.search_fields + [
#         index.SearchField('body'),
#         index.SearchField('excerpt'),
#         index.FilterField('page_ptr_id')
#     ]
# 
#     # Panels
#     content_panels = getattr(Entry, 'content_panels', [])
# 
#     promote_panels = Page.promote_panels + getattr(Entry, 'promote_panels', [])
# 
#     settings_panels = Page.settings_panels + [
#         FieldPanel('date'), FieldPanel('owner'),
#     ] + getattr(Entry, 'settings_panels', [])
# 
#     # Parent and child settings
#     parent_page_types = ['puput.BlogPage']
#     subpage_types = []
# 
#     def get_sitemap_urls(self, request=None):
#         from .urls import get_entry_url
#         root_url = self.get_url_parts()[1]
#         entry_url = get_entry_url(self, self.blog_page.page_ptr, root_url)
#         return [
#             {
#                 'location': root_url + entry_url,
#                 # fall back on latest_revision_created_at if last_published_at is null
#                 # (for backwards compatibility from before last_published_at was added)
#                 'lastmod': (self.last_published_at or self.latest_revision_created_at),
#             }
#         ]
# 
#     @property
#     def blog_page(self):
#         return self.get_parent().specific
# 
#     @property
#     def related(self):
#         return [related.entrypage_to for related in self.related_entrypage_from.all()]
# 
#     @property
#     def has_related(self):
#         return self.related_entrypage_from.count() > 0
# 
#     def get_absolute_url(self):
#         return self.full_url
# 
#     def get_context(self, request, *args, **kwargs):
#         context = super(EntryPage, self).get_context(request, *args, **kwargs)
#         context['blog_page'] = self.blog_page
#         return context
# 
#     class Meta:
#         verbose_name = _('Entry')
#         verbose_name_plural = _('Entries')
# 
# Path: puput/utils.py
# def strip_prefix_and_ending_slash(path):
#     """
#     If puput and wagtail are registered with a prefix, it needs to be removed
#     so the 'entry_page_serve_slug' or 'blog_page_feed_slug' resolutions can work.
#     Ex, here with a dynamic (i18n_patterns()) + a static prefix :
#     urlpatterns += i18n_patterns(
#         url(r'^blah/', include('puput.urls')),
#         url(r'^blah/', include(wagtail_urls)),
#     )
#     The prefix is simply the root where Wagtail page are served.
#     https://github.com/torchbox/wagtail/blob/stable/1.8.x/wagtail/wagtailcore/urls.py#L36
#     """
#     return path.replace(reverse('wagtail_serve', args=[""]), '', 1).rstrip("/")
# 
# def import_model(path_or_callable):
#     if hasattr(path_or_callable, '__call__'):
#         return path_or_callable
#     else:
#         assert isinstance(path_or_callable, str)
#         package, attr = path_or_callable.rsplit('.', 1)
#         return getattr(import_module(package), attr)


# Path: puput/views.py
from django.conf import settings
from django.http import Http404, HttpResponse
from django.views.generic import View
from django.views.decorators.csrf import ensure_csrf_cookie
from django.utils.decorators import method_decorator
from wagtail.core import hooks
from wagtail.core.models import Site
from .models import EntryPage
from .utils import strip_prefix_and_ending_slash, import_model

            # Example:
            # splited_path =  ['es', 'blog', '2016', '06', '23', 'blog-entry']
            # slicing this way you obtain:
            # path_components =  ['es', 'blog', 'blog-entry']
            # with the oldest solution you'll get ['es', 'blog-entry']
            # and a 404 will be raised
            splited_path = strip_prefix_and_ending_slash(request.path).split("/")
            path_components = splited_path[:-4] + splited_path[-1:]
        else:
            path_components = [strip_prefix_and_ending_slash(request.path).split('/')[-1]]
        page, args, kwargs = site.root_page.specific.route(request, path_components)

        for fn in hooks.get_hooks('before_serve_page'):
            result = fn(page, request, args, kwargs)
            if isinstance(result, HttpResponse):
                return result
        return page.serve(request, *args, **kwargs)


class EntryPageUpdateCommentsView(View):

    def post(self, request, entry_page_id, *args, **kwargs):
        try:
            entry_page = EntryPage.objects.get(pk=entry_page_id)
            blog_page = entry_page.blog_page
            comment_class = import_model(settings.PUPUT_COMMENTS_PROVIDER)(blog_page, entry_page)
            num_comments = comment_class.get_num_comments()
            entry_page.num_comments = num_comments
            entry_page.save(update_fields=('num_comments',))
            return HttpResponse()

        except EntryPage.DoesNotExist: