from wagtail.core.models import Page
from django.db import models
from django.conf import settings
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtailmetadata.models import MetadataPageMixin
from bs4 import BeautifulSoup


SHORT_BODY_LENGTH = 30


class Entity(MetadataPageMixin, Page):
    is_home = False

    subtitle = models.CharField(max_length=255)

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    post_date = models.DateTimeField(null=True, blank=True)

    promote_panels = [
        MultiFieldPanel([
            FieldPanel('slug'),
            FieldPanel('seo_title'),
            FieldPanel('post_date'),
            FieldPanel('search_description'),
            ImageChooserPanel('search_image'),
        ], 'Common page configuration'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('subtitle'),
    ]

    @property
    def image(self):
        return self.search_image

    def get_meta_description(self):
        return self.search_description

    def get_page_title(self):
        from . import utils
        return utils.get_page_title(self) + settings.WAGTAIL_SITE_NAME

    def get_short_body(self):
        body_words = BeautifulSoup(str(self.body), 'html5lib').get_text().split(' ')
        ending = '...' if len(body_words) > SHORT_BODY_LENGTH else ''
        return ' '.join(body_words[:SHORT_BODY_LENGTH]) + ending  # limit to 30 words (ish)

    class Meta:
        abstract = True
        ordering = ('title',)
