# Copyright 2021 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""debusine-admin command to remove tokens. Allows filtering."""

import sys

from django.core.management.base import CommandError

from debusine.db.models import Token
from debusine.server.management.debusine_base_command import DebusineBaseCommand
from debusine.server.management.utils import print_tokens


class Command(DebusineBaseCommand):
    """Command to aggregate other sub-commands from different applications."""

    help = (
        "Delete existing tokens. By default it requests confirmation "
        "before deletion"
    )

    input_file = sys.stdin

    def add_arguments(self, parser):
        """Add CLI arguments for the remove-tokens command."""
        parser.add_argument(
            '--yes', action='store_true', help='Skips confirmation of deletion'
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='Does not fail if trying to delete nonexistent tokens',
        )
        parser.add_argument('--token', help='Deletes only this token')
        parser.add_argument('--owner', help='Deletes tokens owner by {owner}')

    def handle(self, *args, **options):
        """Remove (if selected and confirmed) tokens."""
        tokens = Token.objects.get_tokens(
            owner=options['owner'], key=options['token']
        )

        if not tokens:
            error_message = 'There are no tokens to be removed'
            if options['force']:
                self.stdout.write(error_message)
                return
            else:
                raise CommandError(error_message, returncode=3)

        print_tokens(self.stdout, tokens)
        self.stdout.write()

        deletion_confirmed = False
        deletion_forced = options['yes']
        if not deletion_forced:
            self.stdout.write('Would you like to delete them? [yN] ')
            deletion_answer = self.input_file.readline().strip()
            deletion_confirmed = deletion_answer in ('y', 'Y')

        if deletion_forced or deletion_confirmed:
            tokens.delete()
