from datetime import timedelta

from django.db import models
from django.db.models import Q
from django.utils import timezone


class ActiveJobMemberManager(models.Manager):
    """return a list of active member, and members who are still working."""

    def get_all_by_slug(self, slug):
        return (
            self.get_queryset()
            .filter(job__job_group__slug=slug)
            .order_by("job__slug", "job_role", "member__firstname")
        )

    def get_queryset(self):
        date_today = timezone.now().date()
        qs = super().get_queryset().order_by("member__firstname")

        return qs.filter(
            Q(member__role="A") & (Q(job_end__gt=date_today) | Q(job_end__isnull=True))
        )


class InactiveJobMemberManager(models.Manager):
    """return a list of inactive member."""

    def get_all_by_slug(self, slug):
        return (
            self.get_queryset()
            .filter(job__job_group__slug=slug)
            .order_by("job__slug", "job_role", "member__firstname")
        )

    def get_queryset(self):
        date_today = timezone.now().date()
        qs = super().get_queryset().order_by("member__firstname")

        return qs.filter(
            Q(member__role="P")
            | (Q(job_end__lt=date_today + timedelta(days=1)) & Q(job_end__isnull=False))
        )


class JobMemberManager(models.Manager):
    def get_members(self, role):
        qs = self.get_queryset().order_by("member__firstname")

        return qs.filter(Q(member__role=role))


class JobGroupManager(models.Manager):
    def get_pinned_jobgroups(self):
        return self.get_queryset().filter(is_pinned=True)

    def get_unpinned_jobgroups(self):
        return self.get_queryset().filter(is_pinned=False)


class MemberManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().order_by("firstname")
