from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from django.contrib.postgres.fields import ArrayField

from establishment.models import Establishment
from utils.models import ImageMixin, ProjectBaseMixin


class PartnerQueryset(models.QuerySet):

    def with_base_related(self):
        return self.prefetch_related('partnertoestablishment_set', 'country')


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

    PARTNER = 0
    SPONSOR = 1
    MODEL_TYPES = (
        (PARTNER, _('Partner')),
        (SPONSOR, _('Sponsor')),
    )

    old_id = models.PositiveIntegerField(_('old id'), blank=True, null=True, default=None)
    name = models.CharField(_('name'), max_length=255, blank=True, null=True)
    images = ArrayField(
        models.URLField(verbose_name=_('Partner image URL')), blank=True, null=True, default=None,
    )
    establishment = models.ManyToManyField('establishment.Establishment', related_name='partners',
                                           through='PartnerToEstablishment',
                                           verbose_name=_('Establishments'))
    type = models.PositiveSmallIntegerField(choices=MODEL_TYPES, default=PARTNER)
    country = models.ForeignKey('location.Country', null=True, default=None, on_delete=models.SET_NULL)

    objects = PartnerQueryset.as_manager()

    class Meta:
        verbose_name = _('partner')
        verbose_name_plural = _('partners')

    def __str__(self):
        return f'{self.name}'

    @property
    def type_display(self):
        return self.MODEL_TYPES[self.type][1]


class PartnerToEstablishmentQuerySet(models.QuerySet):

    def with_base_related(self):
        return self.prefetch_related('partner', 'partner__country')


class PartnerToEstablishment(models.Model):
    partner_bind_date = models.DateTimeField(default=timezone.now, editable=False,
                                             verbose_name=_('Date partner binded'))
    starting_date = models.DateField(_('starting date'), blank=True, null=True)
    expiry_date = models.DateField(_('expiry date'), blank=True, null=True)
    price_per_month = models.DecimalField(_('price per month'), max_digits=10, decimal_places=2, blank=True, null=True)
    url = models.URLField(verbose_name=_('Establishment to Partner URL'), null=True, blank=True, default=None)
    image = models.URLField(verbose_name=_('Partner image URL'), null=True)
    partner = models.ForeignKey(Partner, on_delete=models.CASCADE, null=True)
    establishment = models.ForeignKey('establishment.Establishment', on_delete=models.CASCADE, null=True)

    objects = PartnerToEstablishmentQuerySet.as_manager()

