import logging

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

from core.models import StaticPage, MailTemplate
from core.tanker.api import Tanker


__all__ = ['update_mail_template_translations', 'update_page_translations']

logger = logging.getLogger(__name__)

TANKER_PREFIX = getattr(settings, 'TANKER_PREFIX', '')


def update_translatable_type(ids_to_translate, tanker_type, update_function):
    updates_counter = 0
    t = Tanker(settings.TANKER_ID)

    keyset_id = '{prefix}_{type}'.format(
        prefix=TANKER_PREFIX,
        type=tanker_type,
    )

    translations = t.download_keyset(keyset_id)

    for (language, k) in translations.iteritems():
        for (identifier, updates) in k.iteritems():
            if not all(updates.itervalues()):
                continue
            if (
                    ids_to_translate is not None and
                    identifier not in ids_to_translate
            ):
                continue

            update_function(identifier, language, updates)
            updates_counter += 1

    return updates_counter


def _update_page(page_type, language, updates):
    language = StaticPage.get_language_code(language)

    page, _ = StaticPage.objects.get_or_create(
        page_type=page_type,
        language=language,
    )

    updates['status'] = StaticPage.STATUS_PUBLISHED

    for k, v in updates.iteritems():
        setattr(page, k, v)
    page.save()


def _update_mail_template(code, language, updates):
    language = MailTemplate.get_language_code(language)

    template, _ = MailTemplate.objects.get_or_create(
        code=code,
        language=language,
    )

    for k, v in updates.iteritems():
        setattr(template, k, v)
    template.save()


@task
@transaction.atomic
def update_page_translations():
    pages_to_translate = set(StaticPage.objects.filter(
        status=StaticPage.STATUS_IN_TANKER,
    ).values_list('page_type', flat=True))

    count = update_translatable_type(
        pages_to_translate,
        StaticPage.TANKER_TYPE,
        _update_page,
    )
    return count


@task
@transaction.atomic
def update_mail_template_translations():
    count = update_translatable_type(
        None,
        MailTemplate.TANKER_TYPE,
        _update_mail_template,
    )
    return count
