# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import logging

from celery import task
from django.db import transaction

import core.utils
from core.models import HallOfFameGroup
from core.models import Reward, Reporter

__all__ = ['generate_for_previous_month']

logger = logging.getLogger(__name__)


@task
def generate_for_previous_month():
    previous_month = core.utils.get_previous_month()
    generate(previous_month.year, previous_month.month)


@task
@transaction.atomic
def generate(year, month):
    considered_rewards_status_list = [
        Reward.ST_NEW,
        Reward.ST_PAYABLE,
        Reward.ST_FINISHED,
        Reward.ST_BAD_DETAILS,
        Reward.ST_UPLOADED_TO_YT,
    ]
    approved_reporters = Reporter.objects.filter(
        rewards__payment_created__year=year,
        rewards__payment_created__month=month,
        rewards__status__in=considered_rewards_status_list).distinct()
    logger.info('Add reporters: %s', approved_reporters.values_list('uid', flat=True))
    hall_of_fame_group, _ = HallOfFameGroup.objects.get_or_create(year=year, month=month)
    hall_of_fame_group.add_members(approved_reporters)
    hall_of_fame_group.publish()
