import os
import subprocess

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


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "-n",
            "--name",
            type=str,
            help="Name of the database to recreate. Default is 'appdb'",
            default="appdb",
        )

        parser.add_argument(
            "-d",
            "--dump",
            type=str,
            help="Path to the dump file",
            default="./fixtures/db.dump",
        )

        parser.add_argument(
            "-ou",
            "--oldurl",
            type=str,
            help="Old URL, e.g. https://envipath.org/",
            default="https://envipath.org/",
        )

        parser.add_argument(
            "-nu",
            "--newurl",
            type=str,
            help="New URL, e.g. http://localhost:8000/",
            default="http://localhost:8000/",
        )

    def handle(self, *args, **options):
        dump_file = options["dump"]

        if not os.path.exists(dump_file):
            raise ValueError(f"Dump file {dump_file} does not exist")

        db_name = options["name"]

        print(f"Dropping database {db_name} y/n: ", end="")

        if input() in "yY":
            result = subprocess.run(
                ["dropdb", db_name],
                capture_output=True,
                text=True,
            )
            print(result.stdout)
        else:
            raise ValueError("Aborted")

        print(f"Creating database {db_name}")

        result = subprocess.run(
            ["createdb", db_name],
            capture_output=True,
            text=True,
        )
        print(result.stdout)
        print(f"Restoring database {db_name} from {dump_file}")

        result = subprocess.run(
            ["pg_restore", "-d", db_name, dump_file, "--no-owner"],
            capture_output=True,
            text=True,
        )
        print(result.stdout)

        if db_name == settings.DATABASES["default"]["NAME"]:
            call_command("localize_urls", "--old", options["oldurl"], "--new", options["newurl"])
        else:
            print("Skipping localize_urls as database is not the default one.")
