from django.contrib import messages
from django.contrib.auth.models import User
from django.shortcuts import render
from django.utils import timezone

from collections import deque

from .forms import TaskForm
from .models import Task, TaskList
from authentications.decorators import authenticated_user


@authenticated_user
def index(request):
    current_user = request.user.id
    current_action = False
    show_tasklist = None
    show_all_tasks = True

    if request.method == "POST":
        if "btn_input" in request.POST:
            form = TaskForm(request.POST)

            if form.is_valid():
                task = form.save(commit=False)

                if task.assigned_to:
                    if TaskList.objects.filter(users=task.assigned_to):
                        task.created_by = request.user
                        task.save()
                    else:
                        messages.info(
                            request,
                            "User '{}' ist nicht in der Liste von Task-Gruppe '{}'.".format(
                                task.assigned_to, task.task_list.name
                            ),
                        )
                else:
                    task.created_by = request.user
                    task.save()

        elif "btn_checkbox" in request.POST:
            for task_id in request.POST.getlist("checkbox"):
                task = Task.objects.get(id=task_id)

                if not task.completed:
                    task.completed = True
                    task.completed_date = timezone.now().date()
                    task.save()

        elif "btn_user" in request.POST:
            if request.POST["action"] == "show_incompleted":
                current_action = False
            else:
                current_action = True

            if request.POST["tasklist"] != "all":
                show_tasklist = TaskList.objects.filter(
                    id=request.POST["tasklist"]
                ).first()

            if request.POST["tasks"] == "all":
                show_all_tasks = True
            else:
                show_all_tasks = False

    form = TaskForm()
    tasks = deque(
        Task.taskmanager.get_tasks(
            user=current_user,
            completed=current_action,
            task_list=show_tasklist,
            all_tasks=show_all_tasks,
        )
    )
    tasklists = deque(TaskList.objects.all())

    context = {
        "formset": form,
        "tasks": tasks,
        "tasklists": tasklists,
        "current_user": current_user,
        "current_action": current_action,
    }

    return render(request, "tasks/index.html", context)
