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

"""Views related to workers."""

from typing import Any

from debusine.db.models import Worker
from debusine.tasks.models import WorkerType
from debusine.web.views.base import BaseUIView, ListViewBase
from debusine.web.views.view_utils import PaginationMixin


class WorkersListView(BaseUIView, PaginationMixin, ListViewBase[Worker]):
    """List workers."""

    model = Worker
    template_name = "web/worker-list.html"
    context_object_name = "worker_list"
    ordering = "name"
    paginate_by = 50

    # Maps URL query parameter names to model field names for sorting
    ORDERING_FIELDS = {
        "name": ["name"],
        "worker_type": ["worker_type"],
        "registered_at": ["registered_at"],
        "last_seen_at": ["token__last_seen_at"],
        "enabled": ["token__enabled"],
    }

    def get_ordering(self) -> list[str]:
        """Return fields used for sorting."""
        order = self.request.GET.get("order", "")
        if order_fields := self.ORDERING_FIELDS.get(order):
            if self.request.GET.get("asc", "0") == "0":
                return [f"-{field}" for field in order_fields]
            else:
                return order_fields

        return ["name"]

    def get_ordering_query_parameter(self) -> str:
        """Return sorting's GET parameter. Default is "name"."""
        if (param := self.request.GET.get("order", "")) in self.ORDERING_FIELDS:
            return param

        return "name"

    def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
        """Add context to the default ListView data."""
        context = super().get_context_data(**kwargs)

        context["order"] = self.get_ordering_query_parameter()

        context["asc"] = self.request.GET.get("asc", "0")

        context["WorkerType"] = {wt.name: wt.value for wt in WorkerType}

        return context
