from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Q
from django.utils import timezone


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 = self.get_queryset().get_ordered().filter(assigned_to__id=user)

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

        if not completed:
            qs = qs.filter(completed=completed)

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

        return qs

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


class TaskList(models.Model):
    name = models.CharField(max_length=60)
    slug = models.SlugField(unique=True, null=True, blank=True)

    users = models.ManyToManyField(User, blank=True)

    objects = models.Manager()

    class Meta:
        verbose_name = "Auf­ga­ben­be­reich"
        verbose_name_plural = "Auf­ga­ben­be­reiche"

    def __str__(self):
        return self.name


class Task(models.Model):
    title = models.CharField(verbose_name="Titel", max_length=140)
    task_list = models.ForeignKey(
        TaskList, verbose_name="Aufgabenbereich", on_delete=models.CASCADE, null=True
    )

    created_date = models.DateTimeField(auto_now_add=True)
    due_date = models.DateField(verbose_name="Fälligkeit", blank=True, null=True)

    completed = models.BooleanField(verbose_name="Abgeschlossen", default=False)
    completed_date = models.DateField(blank=True, null=True)

    created_by = models.ForeignKey(
        User,
        related_name="created_by",
        on_delete=models.CASCADE,
    )
    assigned_to = models.ForeignKey(
        User,
        blank=True,
        null=True,
        related_name="assigned_to",
        on_delete=models.CASCADE,
        verbose_name="Zugewiesen an",
    )

    note = models.TextField(verbose_name="Notizen", blank=True, null=True)
    priority = models.PositiveIntegerField(
        verbose_name="Priorität", blank=True, null=True
    )

    objects = models.Manager()
    taskmanager = TaskManager()

    class Meta:
        verbose_name = "Aufgabe"
        verbose_name_plural = "Aufgaben"

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if self.completed and not self.completed_date:
            self.completed_date = timezone.now().date()

        if not self.completed and self.completed_date:
            self.completed_date = None

        super().save(*args, **kwargs)
