# Path: clubadm/models.py
# class Member(models.Model):
#     user = models.ForeignKey(User, verbose_name="пользователь")
#     season = models.ForeignKey(Season, verbose_name="сезон")
#     giftee = models.OneToOneField("self", related_name="santa",
#                                   verbose_name="получатель подарка",
#                                   blank=True, null=True)
#     fullname = models.CharField("полное имя", max_length=80)
#     postcode = models.CharField("индекс", max_length=20)
#     address = models.TextField("адрес", max_length=200)
#     gift_sent = models.DateTimeField("подарок отправлен", db_index=True,
#                                      blank=True, null=True)
#     gift_received = models.DateTimeField("подарок получен", db_index=True,
#                                          blank=True, null=True)
# 
#     objects = MemberManager()
# 
#     class Meta:
#         verbose_name = "участник"
#         verbose_name_plural = "участники"
#         ordering = ["season", "fullname"]
#         unique_together = ("user", "season")
# 
#     def __str__(self):
#         return "%s (%s)" % (self.fullname, self.season)
# 
#     @property
#     def is_gift_sent(self):
#         return self.gift_sent is not None
# 
#     @property
#     def is_gift_received(self):
#         return self.gift_received is not None
# 
#     def read_mails(self, sender, timestamp):
#         Mail.objects.filter(
#             sender=sender,
#             recipient=self,
#             read_date__isnull=True,
#             send_date__lte=timezone.make_aware(datetime.datetime.fromtimestamp(timestamp)),
#             send_date__gte=timezone.make_aware(datetime.datetime(2016, 12, 20))
#         ).update(read_date=timezone.now())
#         cache.delete(_get_mails_cache_key(self, sender))
# 
#     def send_mail(self, body, recipient):
#         mail = Mail(body=body, sender=self, recipient=recipient)
#         mail.save()
# 
#     def send_gift(self):
#         self.gift_sent = timezone.now()
#         self.save()
# 
#     def receive_gift(self):
#         self.gift_received = timezone.now()
#         self.save()
# 
# class Season(models.Model):
#     year = models.IntegerField("год", primary_key=True)
#     gallery = models.URLField("пост хвастовства подарками", blank=True)
#     signups_start = models.DateField("начало регистрации")
#     signups_end = models.DateField("жеребьевка адресов")
#     ship_by = models.DateField("последний срок отправки подарка", help_text=
#                                "После этой даты сезон закрывается и уходит в"
#                                "архив.")
#     member_count = models.IntegerField("кол-во участников")
#     shipped_count = models.IntegerField("сколько отправили")
#     delivered_count = models.IntegerField("сколько получили")
# 
#     objects = SeasonManager()
# 
#     class Meta:
#         ordering = ["year"]
#         get_latest_by = "year"
#         verbose_name = "сезон"
#         verbose_name_plural = "сезоны"
# 
#     def __str__(self):
#         return "АДМ-%d" % self.year
# 
#     @property
#     def cache_key(self):
#         return "season:%d" % self.pk
# 
#     def save(self, *args, **kwargs):
#         super(Season, self).save(*args, **kwargs)
#         cache.set(self.cache_key, self, timeout=None)
# 
#     def delete(self, *args, **kwargs):
#         super(Season, self).delete(*args, **kwargs)
#         cache.delete(self.cache_key)
# 
#     def get_absolute_url(self):
#         return '/%d/' % self.year
# 
#     @property
#     def is_closed(self):
#         return timezone.now().date() > self.ship_by
# 
#     @property
#     def is_participatable(self):
#         today = timezone.now().date()
#         return today >= self.signups_start and today < self.signups_end


from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season



class SeasonMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        if "year" in view_kwargs:
            year = int(view_kwargs["year"])
            try:
                request.season = Season.objects.get_by_year(year)
            except Season.DoesNotExist:
                raise Http404("Такой сезон еще не создан")


class MemberMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        if "year" in view_kwargs and request.user.is_authenticated:
            year = int(view_kwargs["year"])
            try:
                request.member = Member.objects.get_by_user_and_year(
                    request.user, year)

# Path: clubadm/models.py
# class Member(models.Model):
#     user = models.ForeignKey(User, verbose_name="пользователь")
#     season = models.ForeignKey(Season, verbose_name="сезон")
#     giftee = models.OneToOneField("self", related_name="santa",
#                                   verbose_name="получатель подарка",
#                                   blank=True, null=True)
#     fullname = models.CharField("полное имя", max_length=80)
#     postcode = models.CharField("индекс", max_length=20)
#     address = models.TextField("адрес", max_length=200)
#     gift_sent = models.DateTimeField("подарок отправлен", db_index=True,
#                                      blank=True, null=True)
#     gift_received = models.DateTimeField("подарок получен", db_index=True,
#                                          blank=True, null=True)
# 
#     objects = MemberManager()
# 
#     class Meta:
#         verbose_name = "участник"
#         verbose_name_plural = "участники"
#         ordering = ["season", "fullname"]
#         unique_together = ("user", "season")
# 
#     def __str__(self):
#         return "%s (%s)" % (self.fullname, self.season)
# 
#     @property
#     def is_gift_sent(self):
#         return self.gift_sent is not None
# 
#     @property
#     def is_gift_received(self):
#         return self.gift_received is not None
# 
#     def read_mails(self, sender, timestamp):
#         Mail.objects.filter(
#             sender=sender,
#             recipient=self,
#             read_date__isnull=True,
#             send_date__lte=timezone.make_aware(datetime.datetime.fromtimestamp(timestamp)),
#             send_date__gte=timezone.make_aware(datetime.datetime(2016, 12, 20))
#         ).update(read_date=timezone.now())
#         cache.delete(_get_mails_cache_key(self, sender))
# 
#     def send_mail(self, body, recipient):
#         mail = Mail(body=body, sender=self, recipient=recipient)
#         mail.save()
# 
#     def send_gift(self):
#         self.gift_sent = timezone.now()
#         self.save()
# 
#     def receive_gift(self):
#         self.gift_received = timezone.now()
#         self.save()
# 
# class Season(models.Model):
#     year = models.IntegerField("год", primary_key=True)
#     gallery = models.URLField("пост хвастовства подарками", blank=True)
#     signups_start = models.DateField("начало регистрации")
#     signups_end = models.DateField("жеребьевка адресов")
#     ship_by = models.DateField("последний срок отправки подарка", help_text=
#                                "После этой даты сезон закрывается и уходит в"
#                                "архив.")
#     member_count = models.IntegerField("кол-во участников")
#     shipped_count = models.IntegerField("сколько отправили")
#     delivered_count = models.IntegerField("сколько получили")
# 
#     objects = SeasonManager()
# 
#     class Meta:
#         ordering = ["year"]
#         get_latest_by = "year"
#         verbose_name = "сезон"
#         verbose_name_plural = "сезоны"
# 
#     def __str__(self):
#         return "АДМ-%d" % self.year
# 
#     @property
#     def cache_key(self):
#         return "season:%d" % self.pk
# 
#     def save(self, *args, **kwargs):
#         super(Season, self).save(*args, **kwargs)
#         cache.set(self.cache_key, self, timeout=None)
# 
#     def delete(self, *args, **kwargs):
#         super(Season, self).delete(*args, **kwargs)
#         cache.delete(self.cache_key)
# 
#     def get_absolute_url(self):
#         return '/%d/' % self.year
# 
#     @property
#     def is_closed(self):
#         return timezone.now().date() > self.ship_by
# 
#     @property
#     def is_participatable(self):
#         today = timezone.now().date()
#         return today >= self.signups_start and today < self.signups_end


# Path: clubadm/middleware.py
from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season




class SeasonMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        if "year" in view_kwargs:
            year = int(view_kwargs["year"])
            try:
                request.season = Season.objects.get_by_year(year)
            except Season.DoesNotExist:
                raise Http404("Такой сезон еще не создан")


class MemberMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        if "year" in view_kwargs and request.user.is_authenticated:
            year = int(view_kwargs["year"])
            try:
                request.member = Member.objects.get_by_user_and_year(
                    request.user, year)

            except Member.DoesNotExist: