import os
import tarfile
import tempfile
from os.path import isdir, isfile, join

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

from ocyan.core.fender import config


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

    def add_arguments(self, parser):
        parser.add_argument("path", help="path to the tarbal")
        parser.add_argument(
            "--skip-db",
            action="store_true",
            default=False,
            help="Do not export the database",
        )
        parser.add_argument(
            "--skip-media",
            action="store_true",
            default=False,
            help="Do not export the media folder",
        )

    def handle(self, *args, **options):
        path = options["path"]
        if isfile(path):
            tarname = path
        elif isdir(path):
            tarname = join(path, "%s.tar.gz" % self.project)
        elif path.endswith("tar.gz"):
            tarname = path
        else:
            tarname = "%s.tar.gz" % path

        with tarfile.open(tarname, "w:gz") as tar:
            if options["skip_db"]:
                self.stdout.write(self.style.WARNING("skipping database"))
            else:
                os.umask(0)
                with tempfile.TemporaryDirectory() as tmp:
                    export_dir = join(tmp, self.project)
                    os.chmod(tmp, 0o777)
                    os.mkdir(export_dir, 0o777)
                    db_dump_path = join(export_dir, "db.json")

                    if config.is_webshop:
                        call_command(
                            "dumpdata",
                            "--indent=4",
                            "--exclude=catalogue.ProductCategoryHierarchy",
                            "--output=%s" % db_dump_path,
                        )
                    else:
                        call_command(
                            "dumpdata",
                            "--indent=4",
                            "--all",
                            "--output=%s" % db_dump_path,
                        )

                    tar.add(export_dir, arcname=self.project)

            if options["skip_media"]:
                self.stdout.write(self.style.WARNING("skipping media"))
            else:
                tar.add(settings.MEDIA_ROOT, arcname=join(self.project, "media"))
                tar.add(settings.STATIC_ROOT, arcname=join(self.project, "static"))
