import logging

from collections import deque
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView
from django.urls import reverse_lazy, reverse
from django.utils import timezone

from authentications.decorators import authenticated_user
from documents.api import get_pad_link
from documents.etherpadlib import add_ep_cookie
from fet2020.utils import add_log_action
from intern.models import Topic
from .forms import DocumentCreateForm, TaskCreateForm, TaskUpdateForm
from .models import Document, Task, TaskList

logger = logging.getLogger(__name__)


@authenticated_user
def index(request):
    completed = False
    tasklist = None
    show_tasklist = None
    show_all_tasks = True

    if request.method == "POST":
        if "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()

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

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

        if "open_tasks" in request.GET:
            completed = False

        if "closed_tasks" in request.GET:
            completed = True

    tasks = Task.taskmanager.get_tasks(
        user=request.user.id,
        completed=completed,
        task_list=tasklist,
        all_tasks=show_all_tasks,
    )
    tasklists = TaskList.objects.all()

    context = {
        "tasks": tasks,
        "tasklists": tasklists,
        "current_user": request.user.id,
        "completed": completed,
        "show_tasklist": show_tasklist,
        "show_all_tasks": show_all_tasks,
    }

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


class TaskCreate(LoginRequiredMixin, CreateView):
    model = Task
    success_url = reverse_lazy("tasks:index")
    template_name = "tasks/task_create.html"
    form_class = TaskCreateForm

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        add_log_action(self.request, form, "tasks", "task", True)
        return super().form_valid(form)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["user"] = self.request.user
        return kwargs


class TaskUpdate(LoginRequiredMixin, UpdateView):
    model = Task
    template_name = "tasks/task_update.html"
    form_class = TaskUpdateForm

    task_id = None
    task_list = None

    def form_valid(self, form):
        add_log_action(self.request, form, "tasks", "task", False)
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["task_list"] = self.task_list
        return context

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["task_list"] = self.task_list
        return kwargs

    def get_initial(self):
        self.task_id = self.kwargs.get("pk")
        self.task_list = Task.objects.get(id=self.task_id).task_list

    def get_success_url(self):
        kwargs = {
            "pk": self.task_id,
        }
        return reverse("tasks:task-detail", kwargs=kwargs)


class TaskDetail(LoginRequiredMixin, DetailView):
    model = Task
    success_url = reverse_lazy("tasks:index")
    template_name = "tasks/task_detail.html"

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)

        try:
            response = add_ep_cookie(self.request, response)
        except Exception as e:
            logger.info("Etherpad Server doesn't work. Error: %s", e)

        return response

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        docus = Document.objects.filter(task__id=self.object.id).order_by("-date")
        documents = deque([])
        # list of etherpad url-link of any documents
        for elem in docus:
            documents.append(
                {
                    "title": elem.title,
                    "date": elem.date,
                    "etherpad_key": get_pad_link(elem.etherpad_key),
                }
            )
        context["documents"] = documents

        context["topic"] = Topic.objects.filter(task_list=self.object.task_list).first()

        return context


class DocumentCreate(LoginRequiredMixin, CreateView):
    model = Document
    template_name = "tasks/attachment_create.html"
    form_class = DocumentCreateForm

    task_id = None

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        add_log_action(self.request, form, "tasks", "document", True)
        return super().form_valid(form)

    def get_initial(self):
        self.task_id = self.kwargs.get("pk")

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["task"] = Task.objects.get(pk=self.task_id)

        return context

    def get_success_url(self):
        kwargs = {
            "pk": self.task_id,
        }
        return reverse("tasks:task-detail", kwargs=kwargs)
