from django.core.management.base import BaseCommand, CommandError  # noqa
from django.contrib.auth import get_user_model
import zipfile
import json

from pathlib import Path

from ...utils import (
    import_builtin_pages,
    import_builtin_pages_from_zip,
    import_builtin_images,
    import_builtin_images_from_zip
)


class Command(BaseCommand):
    help = "Import wiki content for an app"

    def add_arguments(self, parser):
        parser.add_argument("file", nargs=1, type=str)
        parser.add_argument("--username", type=str)
        parser.add_argument("--email", type=str)

    def handle(self, *args, **options):
        if not options['file']:
            raise CommandError("No file to import specified")

        filename = Path(options['file'][0]).resolve()
        print(f"Importing from {filename} ...")

        if not filename.exists():
            raise CommandError("File does not exist!")
        if not filename.is_file():
            raise CommandError("Not a file!")

        username = options['username']
        email = options['email']

        user = None
        UserModel = get_user_model()
        if username:
            try:
                user = UserModel.objects.get(username=username)
            except UserModel.DoesNotExist:
                raise CommandError(f"No user with username {username} exists.")
        elif email:
            try:
                user = UserModel.objects.get(email=email)
            except UserModel.DoesNotExist:
                raise CommandError(f"No user with email {email} exists.")

        if zipfile.is_zipfile(filename):
            with zipfile.ZipFile(filename, "r") as zf:
                znames = zf.namelist()
                has_pages = 'pages.json' in znames
                has_images = 'images.json' in znames

            if not has_images and not has_pages:
                raise CommandError("Not a valid zipfile!")

            if has_pages:
                import_builtin_pages_from_zip(filename, user)
            if has_images:
                import_builtin_images_from_zip(filename, user)
        else:
            with open(filename, "rt", encoding="utf-8") as json_file:
                try:
                    json_data = json.loads(json_file.read())
                except Exception:
                    raise CommandError("Given file is not a zip file or json file!")

            has_images = 'images' in json_data
            has_pages = 'pages' in json_data

            if not has_images and not has_pages:
                raise CommandError("Not a valid json file!")

            if has_images:
                import_builtin_images(filename)
            if has_pages:
                import_builtin_pages(filename)
