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

"""UI helpers for collection relations."""

from functools import cached_property
from typing import override

from django.urls import reverse
from django.utils.html import format_html

from debusine.db.models.collections import CollectionRelation
from debusine.web.views import ui_shortcuts
from debusine.web.views.places import ResourcePlace
from debusine.web.views.ui.base import UI


class CollectionRelationUI(UI[CollectionRelation]):
    """UI helpers for CollectionRelation instances."""

    @cached_property
    def place(self) -> ResourcePlace:
        """Return a place to list similar relations for this collection."""
        url = reverse(
            "workspaces:collections:collection_relations:list",
            kwargs={
                "wname": self.instance.source.workspace.name,
                "ccat": self.instance.source.category,
                "cname": self.instance.source.name,
            },
        )

        return ResourcePlace(
            title=f"Relations of {self.instance.source} collection",
            url=url,
            breadcrumb="Relations",
            parent=self.instance.source.ui(self.request).place,
        )

    @override
    def build_ui_shortcuts(self) -> list[ui_shortcuts.UIShortcut]:
        result = super().build_ui_shortcuts()

        if self.can_delete:
            result.append(
                ui_shortcuts.create_collection_relation_delete(self.instance)
            )

        return result

    @cached_property
    def place_delete(self) -> ResourcePlace:
        """Return a place to delete a CollectionRelation."""
        relation = self.instance

        title = format_html(
            "Delete relation for <code>{relation}</code>", relation=relation
        )

        return ResourcePlace(
            title=title,
            url=reverse(
                "workspaces:collections:collection_relations:delete",
                kwargs={
                    "wname": relation.source.workspace.name,
                    "ccat": relation.source.category,
                    "cname": relation.source.name,
                    "pk": relation.pk,
                },
            ),
            parent=self.place,
            breadcrumb="Delete",
        )
