"""Advertisement app models."""
import uuid

from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from main.models import Page
from translation.models import Language
from utils.models import ProjectBaseMixin, ImageMixin, PlatformMixin, URLImageMixin


class AdvertisementQuerySet(models.QuerySet):
    """QuerySet for model Advertisement."""

    def with_base_related(self):
        """Return QuerySet with base related"""
        return self.select_related('page_type') \
                   .prefetch_related('target_languages', 'sites', 'pages')

    def by_page_type(self, page_type: str):
        """Filter Advertisement by page type."""
        return self.filter(page_type__name=page_type)

    def by_country(self, code: str):
        """Filter Advertisement by country code."""
        return self.filter(sites__country__code=code)

    def by_locale(self, locale):
        """Filter by locale."""
        return self.filter(target_languages__locale=locale)

    def valid(self):
        """Return only valid advertisements."""
        return self.filter(end__lte=timezone.now())


class Advertisement(ProjectBaseMixin):
    """Advertisement model."""

    old_id = models.PositiveIntegerField(_('old id'), blank=True, null=True, default=None)
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    url = models.URLField(verbose_name=_('Ad URL'))
    block_level = models.CharField(verbose_name=_('Block level'), max_length=10, blank=True, null=True)
    target_languages = models.ManyToManyField(Language)
    start = models.DateTimeField(null=True,
                                 verbose_name=_('start'))
    end = models.DateTimeField(blank=True, null=True, default=None,
                               verbose_name=_('end'))
    sites = models.ManyToManyField('main.SiteSettings',
                                   related_name='advertisements',
                                   verbose_name=_('site'))
    page_type = models.ForeignKey('main.PageType', on_delete=models.PROTECT,
                                  null=True,
                                  related_name='advertisements',
                                  verbose_name=_('page type'))

    objects = AdvertisementQuerySet.as_manager()

    class Meta:
        verbose_name = _('Advertisement')
        verbose_name_plural = _('Advertisements')

    def __str__(self):
        return str(self.url)

    def delete(self, using=None, keep_parents=False):
        """Overridden delete method."""
        # Delete all related pages.
        self.pages.all().delete()
        return super().delete(using, keep_parents)

    @property
    def mobile_pages(self):
        """Return mobile page"""
        return self.pages.by_platform(Page.MOBILE)

    @property
    def web_pages(self):
        """Return web page"""
        return self.pages.by_platform(Page.WEB)
