import os
import subprocess
import tarfile
import tempfile
from os.path import exists, join

from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import transaction

from wagtail.models import Site

from ocyan.core.fender import config
from ocyan.main import utils


class Command(BaseCommand):
    project = config.get("django", "name", "myproject")

    def add_arguments(self, parser):
        parser.add_argument("path", help="path to the tarbal")

    def handle(self, *args, **options):
        command = "loaddata"
        if config.i18n_enabled:
            command = "i18nloaddata"

        os.umask(0)
        with tempfile.TemporaryDirectory() as tmp:
            os.chmod(tmp, 0o777)
            with tarfile.open(options["path"]) as tar:
                tar.extractall(tmp)

            if not exists(settings.MEDIA_ROOT):
                os.mkdir(settings.MEDIA_ROOT)
            subprocess.check_call(
                [
                    "/usr/bin/rsync",
                    "--archive",
                    "--verbose",
                    join(tmp, self.project, "media", ""),
                    join(settings.MEDIA_ROOT, ""),
                ]
            )

            db_dump_path = join(tmp, self.project, "db.json")

            with transaction.atomic():
                # Delete all underying pages of the homepages. We do this since the paths can differ under there, which will cause issues with importing
                for site in Site.objects.all():
                    site.root_page.get_descendants().delete()

                # Import database dump
                with utils.disable_searchengine_updates():
                    call_command(command, db_dump_path)
