from django.contrib import messages
from django.contrib.auth import views as auth_views
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.utils.html import format_html
from django.utils.translation import gettext as _
from django.views.generic import (
    CreateView,
    DeleteView,
    DetailView,
    ListView,
    TemplateView,
    UpdateView,
)


class IndexView(LoginRequiredMixin, TemplateView):
    template_name = "main/index.html"

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs) | {
            "statements": (
                self.request.user.statement_set.exclude(account__archived=True)
                .order_by("account__id", "-date")
                .distinct("account__id")
            )
        }


class UserMixin(LoginRequiredMixin):
    def get_queryset(self, **kwargs):
        return super().get_queryset().filter(user=self.request.user)

    def get_form_kwargs(self):
        return super().get_form_kwargs() | {
            "user": self.request.user,
        }


class NummiCreateView(UserMixin, CreateView):
    def form_valid(self, form):
        form.instance.user = self.request.user
        self.next = form.data.get("next")
        return super().form_valid(form)

    def get_success_url(self):
        surl = super().get_success_url()
        messages.success(
            self.request,
            format_html(
                "<a href='{surl}'>{name}</a> {msg}",
                surl=surl,
                name=self.object,
                msg=_("was created successfully"),
            ),
        )

        return self.next or surl


class NummiUpdateView(UserMixin, UpdateView):
    pass


class NummiDetailView(UserMixin, DetailView):
    pass


class NummiDeleteView(UserMixin, DeleteView):
    template_name = "main/confirm_delete.html"
    success_url = reverse_lazy("index")

    def get_form_kwargs(self):
        _res = super().get_form_kwargs()
        _res.pop("user")
        return _res


class LoginView(auth_views.LoginView):
    template_name = "main/login.html"
    next_page = "index"


class LogoutView(auth_views.LogoutView):
    next_page = "login"


class NummiListView(UserMixin, ListView):
    pass
