import logging

from django.utils import timezone

from intranet.femida.src.celery_app import app, get_retry_countdown
from intranet.femida.src.utils.lock import locked_task
from statface_client.constants import WEEKLY_SCALE


logger = logging.getLogger(__name__)


@app.task(max_retries=3)
@locked_task
def upload_dictionaries_to_stat(dict_names=None, only_dynamic=True):
    from intranet.femida.src.stats.registry import registry

    failed_dict_names = []

    if dict_names is None:
        if only_dynamic:
            dict_names = registry.dynamic_dictionaries.keys()
        else:
            dict_names = registry.dictionaries.keys()

    logger.info('Uploading %d dictionaries to Stat: %s', len(dict_names), ', '.join(dict_names))

    for dict_name in dict_names:
        dict_class = registry.dictionaries[dict_name]
        try:
            dict_class().upload()
        except Exception:
            logger.exception('Failed during upload `%s` dictionary to Stat', dict_name)
            failed_dict_names.append(dict_name)

    if failed_dict_names:
        upload_dictionaries_to_stat.retry(
            countdown=get_retry_countdown(upload_dictionaries_to_stat.request.retries),
            kwargs={
                'dict_names': failed_dict_names,
                'only_dynamic': only_dynamic,
            }
        )


@app.task(max_retries=5)
@locked_task
def upload_reports_to_stat(report_names=None):
    from intranet.femida.src.stats.registry import registry

    failed_report_names = []

    if report_names is None:
        report_names = registry.reports.keys()

    logger.info('Uploading %d reports to Stat: %s', len(report_names), ', '.join(report_names))

    for report_name in report_names:
        report_class = registry.reports[report_name]
        if report_class.scale == WEEKLY_SCALE:
            if timezone.now().isoweekday() != 7:
                continue

        try:
            report_class().upload_data()
        except Exception:
            logger.exception('Failed during upload `%s` report to Stat', report_name)
            failed_report_names.append(report_name)

    if failed_report_names:
        upload_reports_to_stat.retry(
            countdown=get_retry_countdown(upload_reports_to_stat.request.retries),
            kwargs={
                'report_names': failed_report_names,
            }
        )
