from django.contrib.auth.models import User
from django.views.generic import ListView

from aircox.models import Program


class UserListView(ListView):
    model = User
    queryset = User.objects.all().order_by("first_name").prefetch_related("groups")
    paginate_by = 100
    permission_required = [
        "auth.list_user",
    ]
    template_name = "aircox/dashboard/user_list.html"

    def get_users_programs(self, users):
        groups = {g for u in users for g in u.groups.all()}
        programs = Program.objects.filter(editors_group__in=groups)
        programs = {p.editors_group_id: p for p in programs}

        for user in users:
            user.programs = [programs[g.id] for g in user.groups.all() if g.id in programs]

        return programs

    def get_context_data(self, **kwargs):
        kwargs["programs"] = self.get_users_programs(self.object_list)
        return super().get_context_data(**kwargs)
