# Copyright 2024 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 debusine.db.models import Worker
from debusine.web.views.base import ListViewBase
from debusine.web.views.utils import PaginationMixin


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

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

    def get_ordering(self):
        """Return field used for sorting."""
        order = self.request.GET.get("order")
        if order in (
            "name",
            "worker_type",
            "registered_at",
            "last_seen_at",
            "token__enabled",
        ):
            if self.request.GET["asc"] == "0":
                return "-" + order
            else:
                return order

        return "name"

    def get_context_data(self, **kwargs):
        """Add context to the default ListView data."""
        context = super().get_context_data(**kwargs)

        context["order"] = self.get_ordering().removeprefix("-")

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

        return context
