# 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.

"""Tests for the management command list_workspaces."""

import re
from datetime import timedelta

from django.test import TestCase

from debusine.db.models import (
    FileStore,
    Workspace,
    default_workspace,
)
from debusine.server.management.commands.tests import call_command


class ListWorkspacesCommandTests(TestCase):
    """Test for list_workspaces management command."""

    def test_list_workspaces(self):
        """List workspace command prints workspace information."""
        # workspace_1 is the pre-created default_workspace()

        workspace_2 = Workspace.objects.create_with_name("TestWorkspace2Public")
        workspace_2.public = True
        workspace_2.save()

        workspace_3 = Workspace.objects.create_with_name(
            "TestWorkspace3WithOtherWorkspaces"
        )
        filestore = FileStore.objects.create(
            name="secondary",
            backend=FileStore.BackendChoices.LOCAL,
            configuration={},
        )
        workspace_3.other_file_stores.add(filestore)

        workspace_4 = Workspace.objects.create_with_name(
            "TestWorkspace4WithExpiration"
        )
        workspace_4.default_expiration_delay = timedelta(days=400)
        workspace_4.save()

        stdout, stderr, _ = call_command('list_workspaces')

        self.assertIn(default_workspace().name, stdout)
        self.assertIn(workspace_2.name, stdout)
        self.assertIn(workspace_3.name, stdout)

        public_regex = re.compile(
            f"{default_workspace().public}"
            f".*{workspace_2.public}"
            f".*{workspace_3.public}"
            f".*{workspace_4.public}",
            re.DOTALL,
        )
        self.assertRegex(stdout, public_regex)

        other_regex = re.compile(
            f"{default_workspace().other_file_stores.count()}"
            f".*{workspace_2.other_file_stores.count()}"
            f".*{workspace_3.other_file_stores.count()}"
            f".*{workspace_4.other_file_stores.count()}",
            re.DOTALL,
        )
        self.assertRegex(stdout, other_regex)

        other_regex = re.compile(
            "Never"
            ".*Never"
            ".*Never"
            f".*{workspace_4.default_expiration_delay.days}  ",
            re.DOTALL,
        )
        self.assertRegex(stdout, other_regex)

        self.assertIn(
            f'Number of workspaces: {Workspace.objects.count()}', stdout
        )
