# Path: elephantblog/models.py
# class Entry(Base, ContentModelMixin):
#     is_active = models.BooleanField(_("is active"), default=True, db_index=True)
#     is_featured = models.BooleanField(_("is featured"), default=False, db_index=True)
# 
#     title = models.CharField(_("title"), max_length=100)
#     slug = models.SlugField(_("slug"), max_length=100, unique_for_date="published_on")
#     author = models.ForeignKey(
#         getattr(settings, "AUTH_USER_MODEL", "auth.User"),
#         on_delete=models.CASCADE,
#         related_name="blogentries",
#         limit_choices_to={"is_staff": True},
#         verbose_name=_("author"),
#     )
#     published_on = models.DateTimeField(
#         _("published on"),
#         blank=True,
#         null=True,
#         default=timezone.now,
#         db_index=True,
#         help_text=_("Will be filled in automatically when entry gets published."),
#     )
#     last_changed = models.DateTimeField(_("last change"), auto_now=True, editable=False)
# 
#     categories = models.ManyToManyField(
#         Category, verbose_name=_("categories"), related_name="blogentries", blank=True
#     )
# 
#     objects = EntryManager()
# 
#     class Meta:
#         get_latest_by = "published_on"
#         ordering = ["-published_on"]
#         verbose_name = _("entry")
#         verbose_name_plural = _("entries")
# 
#     def __str__(self):
#         return self.title
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self._old_is_active = self.is_active
# 
#     def save(self, *args, **kwargs):
#         if self.is_active and not self.published_on:
#             self.published_on = timezone.now()
# 
#         super().save(*args, **kwargs)
# 
#     save.alters_data = True
# 
#     def get_absolute_url(self):
#         # The view/template layer always works with visitors' local time.
#         # Therefore, also generate localtime URLs, otherwise visitors will
#         # hit 404s on blog entry URLs generated for them. Unfortunately, this
#         # also means that you cannot send a permalink around half the globe
#         # and expect it to work...
#         # https://code.djangoproject.com/ticket/18794
#         if settings.USE_TZ:
#             pub_date = timezone.localtime(self.published_on)
#         else:
#             pub_date = self.published_on
# 
#         return reverse(
#             "elephantblog_entry_detail",
#             kwargs={
#                 "year": pub_date.strftime("%Y"),
#                 "month": pub_date.strftime("%m"),
#                 "day": pub_date.strftime("%d"),
#                 "slug": self.slug,
#             },
#         )
# 
#     @classmethod
#     def register_extension(cls, register_fn):
#         from .modeladmins import EntryAdmin
# 
#         register_fn(cls, EntryAdmin)
# 
# Path: elephantblog/utils.py
# def entry_list_lookup_related(entry_qs):
#     LookupClass.lookup(entry_qs)
# 
# def same_category_entries(entry):
#     """@return: all entries that have at least one category in common"""
#     return (
#         Entry.objects.active()
#         .filter(
#             categories__in=entry.categories.all(),
#         )
#         .exclude(pk=entry.pk)
#         .distinct()
#     )


from django import template
from django.core.exceptions import FieldError
from django.utils.translation import get_language
from elephantblog.models import Entry
from elephantblog.utils import entry_list_lookup_related, same_category_entries

@register.simple_tag(takes_context=True)
def get_frontpage(context, category=None):
    queryset = Entry.objects.featured()

    try:
        queryset = queryset.filter(language=get_language())
    except (AttributeError, FieldError):
        pass

    if category:
        queryset = queryset.filter(categories__translations__title=category).distinct()

    context["entries"] = queryset
    return ""


@register.simple_tag(takes_context=True)
def get_others(context, number=3, same_category=True, featured_only=False):
    """This tag can be used on an entry detail page to tease
    other related entries
    """
    if same_category:
        entries = same_category_entries(context["object"])
    else:
        entries = Entry.objects.exclude(pk=context["object"].pk)
    if featured_only:
        entries.filter(is_featured=True)

    entries = entries[:number]

# Path: elephantblog/models.py
# class Entry(Base, ContentModelMixin):
#     is_active = models.BooleanField(_("is active"), default=True, db_index=True)
#     is_featured = models.BooleanField(_("is featured"), default=False, db_index=True)
# 
#     title = models.CharField(_("title"), max_length=100)
#     slug = models.SlugField(_("slug"), max_length=100, unique_for_date="published_on")
#     author = models.ForeignKey(
#         getattr(settings, "AUTH_USER_MODEL", "auth.User"),
#         on_delete=models.CASCADE,
#         related_name="blogentries",
#         limit_choices_to={"is_staff": True},
#         verbose_name=_("author"),
#     )
#     published_on = models.DateTimeField(
#         _("published on"),
#         blank=True,
#         null=True,
#         default=timezone.now,
#         db_index=True,
#         help_text=_("Will be filled in automatically when entry gets published."),
#     )
#     last_changed = models.DateTimeField(_("last change"), auto_now=True, editable=False)
# 
#     categories = models.ManyToManyField(
#         Category, verbose_name=_("categories"), related_name="blogentries", blank=True
#     )
# 
#     objects = EntryManager()
# 
#     class Meta:
#         get_latest_by = "published_on"
#         ordering = ["-published_on"]
#         verbose_name = _("entry")
#         verbose_name_plural = _("entries")
# 
#     def __str__(self):
#         return self.title
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self._old_is_active = self.is_active
# 
#     def save(self, *args, **kwargs):
#         if self.is_active and not self.published_on:
#             self.published_on = timezone.now()
# 
#         super().save(*args, **kwargs)
# 
#     save.alters_data = True
# 
#     def get_absolute_url(self):
#         # The view/template layer always works with visitors' local time.
#         # Therefore, also generate localtime URLs, otherwise visitors will
#         # hit 404s on blog entry URLs generated for them. Unfortunately, this
#         # also means that you cannot send a permalink around half the globe
#         # and expect it to work...
#         # https://code.djangoproject.com/ticket/18794
#         if settings.USE_TZ:
#             pub_date = timezone.localtime(self.published_on)
#         else:
#             pub_date = self.published_on
# 
#         return reverse(
#             "elephantblog_entry_detail",
#             kwargs={
#                 "year": pub_date.strftime("%Y"),
#                 "month": pub_date.strftime("%m"),
#                 "day": pub_date.strftime("%d"),
#                 "slug": self.slug,
#             },
#         )
# 
#     @classmethod
#     def register_extension(cls, register_fn):
#         from .modeladmins import EntryAdmin
# 
#         register_fn(cls, EntryAdmin)
# 
# Path: elephantblog/utils.py
# def entry_list_lookup_related(entry_qs):
#     LookupClass.lookup(entry_qs)
# 
# def same_category_entries(entry):
#     """@return: all entries that have at least one category in common"""
#     return (
#         Entry.objects.active()
#         .filter(
#             categories__in=entry.categories.all(),
#         )
#         .exclude(pk=entry.pk)
#         .distinct()
#     )


# Path: elephantblog/templatetags/blog_widgets.py
from django import template
from django.core.exceptions import FieldError
from django.utils.translation import get_language
from elephantblog.models import Entry
from elephantblog.utils import entry_list_lookup_related, same_category_entries


@register.simple_tag(takes_context=True)
def get_frontpage(context, category=None):
    queryset = Entry.objects.featured()

    try:
        queryset = queryset.filter(language=get_language())
    except (AttributeError, FieldError):
        pass

    if category:
        queryset = queryset.filter(categories__translations__title=category).distinct()

    context["entries"] = queryset
    return ""


@register.simple_tag(takes_context=True)
def get_others(context, number=3, same_category=True, featured_only=False):
    """This tag can be used on an entry detail page to tease
    other related entries
    """
    if same_category:
        entries = same_category_entries(context["object"])
    else:
        entries = Entry.objects.exclude(pk=context["object"].pk)
    if featured_only:
        entries.filter(is_featured=True)

    entries = entries[:number]

    entries = entries.transform(entry_list_lookup_related)