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


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

        if not assigned_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)
