import tarfile
from pathlib import Path

from django.conf import settings
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.core.management import call_command
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import get_language

from wagtail.models import Locale, Site

from ocyan.core.signals import post_loaddemodata, pre_loaddemodata
from ocyan.core.utils import find_fixture
from ocyan.main.signals import pre_import_destructive

from .models import OcyanSettings


@receiver(post_save, sender=OcyanSettings)
def clear_footer_cache(sender, instance, **kwargs):  # pylint: disable=W0613
    for site in Site.objects.all():
        cache.delete(
            make_template_fragment_key("footer", vary_on=[get_language(), site])
        )
        cache.delete(
            make_template_fragment_key(
                "header_4_content", vary_on=[get_language(), site]
            )
        )


@receiver(pre_loaddemodata)
def import_wagtail_images(has_unloaded_fixtures, **kwargs):  # pylint: disable=W0613
    if has_unloaded_fixtures:
        # unpack the original_images tarball
        #
        # this file is not in this plugin because it would always be installed
        # if wagtail is needed, that is why it is stored in the demo_data
        # plugin, if you remove the demo_data plugin the tarball is also gone
        images_path = find_fixture("demo_data/original_images.tar.gz")
        if images_path is not None:
            target_path = Path(settings.MEDIA_ROOT) / "original_images"
            target_path.mkdir(parents=True, exist_ok=True)
            with tarfile.open(images_path, "r:gz") as tar:
                tar.extractall(str(target_path))


@receiver(post_loaddemodata)
def run_set_url_paths(has_unloaded_fixtures, **kwargs):  # pylint: disable=W0613
    if has_unloaded_fixtures:
        # make sure the menu urls don't have None as an url
        call_command("set_url_paths")


@receiver(pre_import_destructive)
def create_default_locale(sender, **kwargs):  # pylint: disable=unused-argument
    Locale.objects.get_or_create(language_code=settings.LANGUAGE_CODE)
