from django.core.management import BaseCommand

from isapilib.api.models import DatabaseAPI


class Command(BaseCommand):
    help = 'Check connection to external database'

    def add_arguments(self, parser):
        parser.add_argument(
            "database",
            help="Nominates a DatabaseAPI primary key to check connectivity",
            type=int,
        )

    def handle(self, *args, **options):
        try:
            databaseapi = DatabaseAPI.objects.get(pk=options["database"])
            name = databaseapi.get_name()

            result, description = databaseapi.verify_connection()
            if result:
                self.stdout.write(self.style.SUCCESS(f'Connection to database {name} was successful.'))
            else:
                self.stdout.write(self.style.SUCCESS(f'Failed to connect to database {name}: {description}'))

        except DatabaseAPI.DoesNotExist:
            self.stdout.write(self.style.SUCCESS(f"Database doesn't exist."))
