# Path: core/models.py
# class Scheduler(models.Model):
#     WEEK_UNIT_CHOICE = 'week'
#     MONTH_UNIT_CHOICE = 'month'
# 
#     UNIT_CHOICES = (
#         (WEEK_UNIT_CHOICE, 'Неделя'),
#         (MONTH_UNIT_CHOICE, 'Месяц'),
#     )
# 
#     UNIT_VERBOSE_CHOICES = {
#         WEEK_UNIT_CHOICE: 'неделю',
#         MONTH_UNIT_CHOICE: 'месяц'
#     }
# 
#     users = models.ManyToManyField(User, related_name='schedulers', blank=True, verbose_name='Пользователь')
#     departments = models.ManyToManyField(Department, related_name='schedulers', blank=True, verbose_name='Отдел')
# 
#     examination = models.ForeignKey(Examination, related_name='schedulers', verbose_name='Тестирование')
# 
#     count = models.PositiveSmallIntegerField(verbose_name='Сколько раз повторять')
#     period = models.PositiveSmallIntegerField(verbose_name='Как часто повторять')
#     unit = models.CharField(max_length=255, choices=UNIT_CHOICES, default=WEEK_UNIT_CHOICE,
#                             verbose_name='Единица измерения периода',
#                             help_text='Например: 1 раз в 2 месяца, 3 раза в 1 неделю')
# 
#     is_active = models.BooleanField(default=False, verbose_name='В работе')
# 
#     class Meta:
#         verbose_name = 'расписание'
#         verbose_name_plural = 'Расписания'
# 
#     def __str__(self):
#         return str(self.id)
# 
#     def get_verbose_period(self):
#         if self.period != 1:
#             verb = '{count} раз в {period} {unit}'
#         else:
#             verb = '{count} раз в {unit}'
# 
#         try:
#             if self.period % 100 in (11, 12, 13, 14):
#                 unit = 'недель' if self.unit == self.WEEK_UNIT_CHOICE else 'месяцев'
#             elif self.period % 10 == 1:
#                 unit = 'неделю' if self.unit == self.WEEK_UNIT_CHOICE else 'месяц'
#             elif self.period % 10 in (2, 3, 4):
#                 unit = 'недели' if self.unit == self.WEEK_UNIT_CHOICE else 'месяца'
#             else:
#                 unit = 'недель' if self.unit == self.WEEK_UNIT_CHOICE else 'месяцев'
#         except:
#             raise AttributeError
# 
#         return verb.format(unit=unit, count=self.count, period=self.period)
# 
#     def get_timedelta(self):
#         if self.unit == 'month':
#             timedelta = relativedelta(months=-1)
#         elif self.unit == 'week':
#             timedelta = relativedelta(weeks=-1)
#         else:
#             raise AttributeError
# 
#         return timedelta
# 
#     def get_next(self, from_dt=None):
#         return self.get_datetime_for_check_period(from_dt, for_future=True)
# 
#     def get_datetime_for_check_period(self, from_dt=None, for_future=False):
#         end_period = from_dt or datetime.datetime.now()
#         if for_future:
#             start_period = end_period + self.get_timedelta()
#         else:
#             start_period = end_period - self.get_timedelta()
# 
#         period_seconds = (start_period - end_period).total_seconds()
# 
#         return end_period - datetime.timedelta(
#             seconds=float(self.period) / self.count * period_seconds  # TODO подумать над названиями полей(period!)
#         )
# 
#     def get_users(self):
#         users = {}
# 
#         for department in self.departments.all():
#             for user in department.employees.all():
#                 users[user.id] = user
# 
#         for user in self.users.all():
#             users[user.id] = user
# 
#         return users.values()
# 
#     @classmethod
#     def check_user_examinations(cls):
# 
#         now = datetime.datetime.now()
# 
#         for scheduler in cls.objects.filter(is_active=True):
#             scheduler_from_dt = scheduler.get_datetime_for_check_period(now)
#             examination = scheduler.examination
# 
#             for user in scheduler.get_users():
#                 if not UserExamination.objects.filter(
#                     user=user, examination=examination, available_from__gte=scheduler_from_dt
#                 ).exists():
#                     UserExamination.objects.create(
#                         examination=examination, user=user, available_from=now,
#                         complete_until=now + datetime.timedelta(days=7), scheduler=scheduler
#                         # TODO hard code 7 days
#                     )


import time
from core.models import Scheduler
from django.core.management.base import BaseCommand
# -*- coding: utf-8 -*-




class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('-i', '--infinite',
            action='store_true',
            dest='infinite',
            default=False,
            help='Run infinite loop'
        )

    def handle(self, *args, **options):
        if options['infinite']:
            while True:
                Scheduler.check_user_examinations()
                time.sleep(60)
        else:

# Path: core/models.py
# class Scheduler(models.Model):
#     WEEK_UNIT_CHOICE = 'week'
#     MONTH_UNIT_CHOICE = 'month'
# 
#     UNIT_CHOICES = (
#         (WEEK_UNIT_CHOICE, 'Неделя'),
#         (MONTH_UNIT_CHOICE, 'Месяц'),
#     )
# 
#     UNIT_VERBOSE_CHOICES = {
#         WEEK_UNIT_CHOICE: 'неделю',
#         MONTH_UNIT_CHOICE: 'месяц'
#     }
# 
#     users = models.ManyToManyField(User, related_name='schedulers', blank=True, verbose_name='Пользователь')
#     departments = models.ManyToManyField(Department, related_name='schedulers', blank=True, verbose_name='Отдел')
# 
#     examination = models.ForeignKey(Examination, related_name='schedulers', verbose_name='Тестирование')
# 
#     count = models.PositiveSmallIntegerField(verbose_name='Сколько раз повторять')
#     period = models.PositiveSmallIntegerField(verbose_name='Как часто повторять')
#     unit = models.CharField(max_length=255, choices=UNIT_CHOICES, default=WEEK_UNIT_CHOICE,
#                             verbose_name='Единица измерения периода',
#                             help_text='Например: 1 раз в 2 месяца, 3 раза в 1 неделю')
# 
#     is_active = models.BooleanField(default=False, verbose_name='В работе')
# 
#     class Meta:
#         verbose_name = 'расписание'
#         verbose_name_plural = 'Расписания'
# 
#     def __str__(self):
#         return str(self.id)
# 
#     def get_verbose_period(self):
#         if self.period != 1:
#             verb = '{count} раз в {period} {unit}'
#         else:
#             verb = '{count} раз в {unit}'
# 
#         try:
#             if self.period % 100 in (11, 12, 13, 14):
#                 unit = 'недель' if self.unit == self.WEEK_UNIT_CHOICE else 'месяцев'
#             elif self.period % 10 == 1:
#                 unit = 'неделю' if self.unit == self.WEEK_UNIT_CHOICE else 'месяц'
#             elif self.period % 10 in (2, 3, 4):
#                 unit = 'недели' if self.unit == self.WEEK_UNIT_CHOICE else 'месяца'
#             else:
#                 unit = 'недель' if self.unit == self.WEEK_UNIT_CHOICE else 'месяцев'
#         except:
#             raise AttributeError
# 
#         return verb.format(unit=unit, count=self.count, period=self.period)
# 
#     def get_timedelta(self):
#         if self.unit == 'month':
#             timedelta = relativedelta(months=-1)
#         elif self.unit == 'week':
#             timedelta = relativedelta(weeks=-1)
#         else:
#             raise AttributeError
# 
#         return timedelta
# 
#     def get_next(self, from_dt=None):
#         return self.get_datetime_for_check_period(from_dt, for_future=True)
# 
#     def get_datetime_for_check_period(self, from_dt=None, for_future=False):
#         end_period = from_dt or datetime.datetime.now()
#         if for_future:
#             start_period = end_period + self.get_timedelta()
#         else:
#             start_period = end_period - self.get_timedelta()
# 
#         period_seconds = (start_period - end_period).total_seconds()
# 
#         return end_period - datetime.timedelta(
#             seconds=float(self.period) / self.count * period_seconds  # TODO подумать над названиями полей(period!)
#         )
# 
#     def get_users(self):
#         users = {}
# 
#         for department in self.departments.all():
#             for user in department.employees.all():
#                 users[user.id] = user
# 
#         for user in self.users.all():
#             users[user.id] = user
# 
#         return users.values()
# 
#     @classmethod
#     def check_user_examinations(cls):
# 
#         now = datetime.datetime.now()
# 
#         for scheduler in cls.objects.filter(is_active=True):
#             scheduler_from_dt = scheduler.get_datetime_for_check_period(now)
#             examination = scheduler.examination
# 
#             for user in scheduler.get_users():
#                 if not UserExamination.objects.filter(
#                     user=user, examination=examination, available_from__gte=scheduler_from_dt
#                 ).exists():
#                     UserExamination.objects.create(
#                         examination=examination, user=user, available_from=now,
#                         complete_until=now + datetime.timedelta(days=7), scheduler=scheduler
#                         # TODO hard code 7 days
#                     )


# Path: core/management/commands/schedule.py
import time
from core.models import Scheduler
from django.core.management.base import BaseCommand

# -*- coding: utf-8 -*-




class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('-i', '--infinite',
            action='store_true',
            dest='infinite',
            default=False,
            help='Run infinite loop'
        )

    def handle(self, *args, **options):
        if options['infinite']:
            while True:
                Scheduler.check_user_examinations()
                time.sleep(60)
        else:

            Scheduler.check_user_examinations()