# Copyright 2022 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 manage workers."""

from django.core.management.base import CommandError

from debusine.db.models import Worker
from debusine.server.management.debusine_base_command import DebusineBaseCommand


class Command(DebusineBaseCommand):
    """Command to manage workers. E.g. enable and disable them."""

    help = 'Enables and disables workers'

    def add_arguments(self, parser):
        """Add CLI arguments for the manage_worker command."""
        parser.add_argument(
            'action',
            choices=['enable', 'disable'],
            help='Enable or disable the worker',
        )
        parser.add_argument('worker', help='Name of the worker to modify')

    def handle(self, *args, **options):
        """Enable or disable the worker."""
        worker = Worker.objects.get_worker_or_none(options['worker'])
        if worker is None:
            worker = Worker.objects.get_worker_by_token_key_or_none(
                options['worker']
            )

        if worker is None:
            raise CommandError('Worker not found', returncode=3)
        if worker.internal:
            raise CommandError(
                'Cannot enable/disable internal worker', returncode=4
            )

        action = options['action']

        if action == 'enable':
            worker.token.enable()
        elif action == 'disable':
            worker.token.disable()
        else:  # pragma: no cover
            pass  # Never reached
