# -*- coding: utf-8 -*-
# Future imports
from __future__ import unicode_literals

# Django imports
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.template.loader import select_template
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _

# Third Party
from cms.models import CMSPlugin
from cms.models.fields import PageField


###################################################################################################
###################################################################################################
class HighlightedContentPluginBase(CMSPlugin):

    title = models.CharField(
        verbose_name=_('Title'),
        max_length=255,
        blank=True, null=True,
        help_text=_('Title to display before the list'))
    page_link = PageField(
        verbose_name=_('Link for the title if set'),
        null=True, blank=True,
        help_text=_('Page displaying all elements'))

    def __str__(self):
        if self.title:
            return '%s "%s"' % (self._meta.verbose_name, self.title)
        return force_str(self._meta.verbose_name)

    class Meta:
        abstract = True
        verbose_name = _('highlighted_content')
        verbose_name_plural = _('highlighted_contents')

    def get_items_count(self):
        if not hasattr(self, '_items_count'):
            items = self.get_items()
            if hasattr(items, 'count') and callable(items.count):
                self._items_count = items.count()
            else:
                self._items_count = len(items)
        return self._items_count

    def get_items(self):
        if hasattr(self, 'items'):
            return self.items.all()
        else:
            raise Exception(('Must be overwrited if you do not use "items" as the related '
                             'name of your highlighted_content ForeignKey'))

    def copy_relations(self, oldinstance):
        """
        copies highlighted_content items when publishing the draft plugin
        see http://docs.django-cms.org/en/develop/how_to/custom_plugins.html#handling-relations
        """
        self.get_items().delete()
        for item in oldinstance.get_items():
            item.pk = None
            item.highlighted_content = self
            item.save()


###################################################################################################
###################################################################################################
class HighlightedContentItemBase(models.Model):

    order = models.PositiveSmallIntegerField(
        verbose_name=_('order'),
        blank=False, null=False, default=0,
        editable=True, db_index=True,
    )
    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        related_name='+',
        verbose_name=_('Item\'s type'),
    )
    object_id = models.PositiveIntegerField(verbose_name=_('Item\'s ID'))
    item = GenericForeignKey()
    # highlighted_content = models.ForeignKey(YourHighlightedContentPluginModel,
    #                                         related_name='items')

    _templates = {}

    class Meta:
        abstract = True
        verbose_name = _('item')
        verbose_name_plural = _('items')
        ordering = ['order']

    def __str__(self):
        return force_str(self.item)

    def save(self, *args, **kwargs):
        if not self.pk and not self.order:
            manager = self.__class__.objects
            self.order = manager.filter(highlighted_content=self.highlighted_content).count() + 1
        super(HighlightedContentItemBase, self).save(*args, **kwargs)

    def get_template(self):
        """returns the template to use to render this item as a item"""
        if self.content_type_id not in self._templates:
            kwargs = {'app_label': self.content_type.app_label,
                      'model_name': self.content_type.model}
            templates = ['%(app_label)s/%(model_name)s/highlighted_content_item.html' % kwargs,
                         '%(app_label)s/highlighted_content_item.html' % kwargs,
                         'cms_highlighted_content/highlighted_content_item.html']
            self._templates[self.content_type_id] = select_template(templates).template.name
        return self._templates[self.content_type_id]