"""Recipe app models."""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils.models import (TranslatedFieldsMixin, ImageMixin, BaseAttributes,
                          TJSONField)


class RecipeQuerySet(models.QuerySet):
    """Extended queryset for Recipe model."""

    # todo: what records are considered published?
    def published(self):
        # TODO: проверка по полю published_at
        return self.filter(state__in=[self.model.PUBLISHED,
                                      self.model.PUBLISHED_EXCLUSIVE])

    def annotate_in_favorites(self, user):
        """Annotate flag in_favorites"""
        favorite_recipe_ids = []
        if user.is_authenticated:
            favorite_recipe_ids = user.favorite_recipe_ids
        return self.annotate(in_favorites=models.Case(
            models.When(
                id__in=favorite_recipe_ids,
                then=True),
            default=False,
            output_field=models.BooleanField(default=False)))

    def by_locale(self, locale):
        return self.filter(title__icontains=locale)


class Recipe(TranslatedFieldsMixin, ImageMixin, BaseAttributes):
    """Recipe model."""

    WAITING = 0
    HIDDEN = 1
    PUBLISHED = 2
    PUBLISHED_EXCLUSIVE = 3

    STATE_CHOICES = (
        (WAITING, _('Waiting')),
        (HIDDEN, _('Hidden')),
        (PUBLISHED, _('Published')),
        (PUBLISHED_EXCLUSIVE, _('Published exclusive')),
    )

    STR_FIELD_NAME = 'title'

    title = TJSONField(blank=True, null=True, default=None, verbose_name=_('Title'), help_text='{"en-GB": "some text"}')
    subtitle = TJSONField(blank=True, null=True, default=None, verbose_name=_('Subtitle'),
                          help_text='{"en-GB": "some text"}')
    description = TJSONField(blank=True, null=True, default=None, verbose_name=_('Description'),
                             help_text='{"en-GB": "some text"}')
    state = models.PositiveSmallIntegerField(default=WAITING, choices=STATE_CHOICES, verbose_name=_('State'))
    author = models.CharField(max_length=255, blank=True, null=True, default=None, verbose_name=_('Author'))
    published_at = models.DateTimeField(verbose_name=_('Published at'), blank=True, default=None, null=True,
                                        help_text=_('Published at'))
    published_scheduled_at = models.DateTimeField(verbose_name=_('Published scheduled at'), blank=True, default=None,
                                                  null=True, help_text=_('Published scheduled at'))
    old_id = models.PositiveIntegerField(_('old id'), blank=True, null=True, default=None)
    slug = models.SlugField(unique=True, max_length=255, null=True, verbose_name=_('Slug'))

    objects = RecipeQuerySet.as_manager()

    class Meta:
        """Meta class."""

        verbose_name = _('Recipe')
        verbose_name_plural = _('Recipes')

    # TODO: в save добавить обновление published_at если state в PUBLISHED или PUBLISHED_EXCLUSIVE
    # TODO: в save добавить обновление published_at в None если state в WAITING или HIDDEN
