from django.db import models
from django.db.models import Q


class TaskQuerySet(models.QuerySet):
    def get_ordered(self):
        return self.order_by("task_list")


class TaskManager(models.Manager):
    def get_tasks(self, user, completed, task_list, all_tasks):
        # None ... assigned to all users
        qs_all = self.get_queryset().get_ordered()
        qs = qs_all.filter(assigned_to__id=user)

        if all_tasks:
            qs_tmp = qs_all.filter(
                Q(assigned_to=None) & Q(task_list__users__id__exact=user)
            )
            qs = (qs | qs_tmp).distinct()

        if task_list:
            qs = qs.filter(task_list=task_list)

        return qs.filter(completed=completed)

    def get_queryset(self):
        return TaskQuerySet(self.model, using=self._db)
