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

import requests
from celery import shared_task
from celery.schedules import crontab
from celery.task import periodic_task
from django_elasticsearch_dsl.registries import registry

from establishment import models
from location.models import Country

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()


@shared_task
def update_establishment_image_urls(part_number: int, summary_tasks: int, bucket_ids: list):
    queryset = models.Establishment.objects.filter(id__in=bucket_ids)

    for establishment in queryset:
        live_link = None

        image_urls = [
            ('image_url', establishment.image_url),
            ('preview_image_url', establishment.preview_image_url)
        ]

        for data in image_urls:
            attr, url = data

            if establishment.image_url is not None:
                try:
                    response = requests.get(url, allow_redirects=True)

                    if response.status_code != 200:
                        setattr(establishment, attr, None)

                    else:
                        live_link = url

                except (
                        requests.exceptions.ConnectionError,
                        requests.exceptions.ConnectTimeout
                ):
                    setattr(establishment, attr, None)

        if live_link is not None:
            if establishment.image_url is None:
                establishment.image_url = live_link

            elif establishment.preview_image_url is None:
                establishment.preview_image_url = live_link
        
        establishment.save()
        
    logger.info(f'The {part_number}th part of the image update '
                f'from {summary_tasks} parts was completed')
