# coding: utf-8
from django.utils import timezone

from idm.core.constants.action import ACTION
from idm.core.models import Action
from idm.core.management.base import IdmBaseCommand


def count_reviews_in_interval(interval_begin, interval_end):
    return Action.objects.filter(
        added__range=(interval_begin, interval_end),
        action=ACTION.REVIEW_REREQUEST
    ).count()


def count_reviews_for_year():
    end_date = timezone.now().date()
    start_date = end_date - timezone.timedelta(days=365)
    one_day = timezone.timedelta(days=1)
    reviews_by_day = dict()
    while start_date <= end_date:
        reviews_by_day[str(start_date)] = count_reviews_in_interval(start_date, start_date + one_day)
        start_date += one_day
    return reviews_by_day


class Command(IdmBaseCommand):
    help = """Этот скрипт подсчитывает количество пересмотров ролей за последний год"""

    intranet_only = True

    def idm_handle(self, *args, **options):
        reviews_by_day = count_reviews_for_year()
        print('Date,Reviews')
        for (day, reviews) in reviews_by_day.items():
            print(day, reviews, sep=',')
