# Copyright 2023 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 workspaces."""

from datetime import timedelta

from django.core.management import CommandError

from debusine.db.models import FileStore, Workspace
from debusine.server.management.debusine_base_command import DebusineBaseCommand


class Command(DebusineBaseCommand):
    """Command to manage workspaces."""

    help = "Manage workspaces"

    def add_arguments(self, parser):
        """Add CLI arguments for the manage_workspace command."""
        parser.add_argument("name", help="Name to modify")
        public = parser.add_mutually_exclusive_group()
        public.add_argument("--public", action="store_true", default=None)
        public.add_argument(
            "--private",
            action="store_false",
            dest="public",
            help='Public permissions (default: private)',
        )
        parser.add_argument(
            "--default-expiration-delay",
            action="store",
            type=int,
            metavar="N",
            help="Minimal time (in days) that a new artifact is kept in the"
            " workspace before being expired (default: 0)",
        )
        parser.add_argument(
            "--default-file-store",
            metavar="NAME",
            help="Name of the default file store to use for this workspace",
        )

    def handle(self, *args, **options):
        """Manage the workspace."""
        name = options["name"]
        try:
            workspace = Workspace.objects.get(name=name)
        except Workspace.DoesNotExist:
            raise CommandError(f'Workspace "{name}" not found', returncode=3)

        if options["public"] is not None:
            workspace.public = options["public"]
        if options["default_expiration_delay"] is not None:
            workspace.default_expiration_delay = timedelta(
                days=options["default_expiration_delay"]
            )
        try:
            if options["default_file_store"]:
                workspace.default_file_store = FileStore.objects.get(
                    name=options["default_file_store"]
                )
        except FileStore.DoesNotExist:
            raise CommandError(
                f'File store "{options["default_file_store"]}" not found',
                returncode=3,
            )
        workspace.save()

        raise SystemExit(0)
