"""Establishment app tasks."""
import logging

from celery import shared_task
from celery.schedules import crontab
from celery.task import periodic_task

from django.core import management
from django_elasticsearch_dsl.management.commands import search_index

from django_elasticsearch_dsl.registries import registry
from establishment import models
from location.models import Country
from search_indexes.documents.establishment import EstablishmentDocument

logger = logging.getLogger(__name__)


@shared_task
def recalculate_price_levels_by_country(country_id):
    try:
        country = Country.objects.get(pk=country_id)
    except Country.DoesNotExist as _:
        logger.error(f'ESTABLISHMENT. Country does not exist. ID {country_id}')
    else:
        qs = models.Establishment.objects.filter(address__city__country=country)
        for establishment in qs:
            establishment.recalculate_price_level(low_price=country.low_price,
                                                  high_price=country.high_price)

# @periodic_task(run_every=crontab(minute=59))
# def rebuild_establishment_indices():
#     management.call_command(search_index.Command(), action='populate', models=[models.Establishment.__name__],
#                             force=True)


@periodic_task(run_every=crontab(minute=59))
def update_establishment_indices():
    try:
        doc = registry.get_documents([models.Establishment]).pop()
    except KeyError:
        pass
    else:
        qs = doc().get_indexing_queryset()
        doc().update(qs)


@shared_task
def recalculation_public_mark(establishment_id):
    establishment = models.Establishment.objects.get(id=establishment_id)
    establishment.recalculate_public_mark()
    establishment.recalculate_toque_number()
