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

import datetime
import logging

from celery import task
from django.conf import settings
from django.db import transaction

from core import models
from core.utils import dates


__all__ = ['assign_automatic_badges']

logger = logging.getLogger(__name__)


@task
@transaction.atomic
def assign_automatic_badges(check_interval=models.Badge.CI_DAY):
    badges = models.Badge.objects.filter(
        is_automatic=True,
        is_active=True,
        check_interval=check_interval,
    )
    for badge in badges:
        badge.assign_by_trigger()


@task
def deprive_overdue_yandex_sponsored_awards(badge_id):
    sponsored_duration = settings.YANDEX_SPONSORED_DURATION
    period_start = dates.today() - datetime.timedelta(sponsored_duration)
    overdue_awards = models.UserBadge.active.filter(
        badge_id=badge_id, activated__lte=period_start)
    for award in overdue_awards.all():
        award.deactivate()
