from django.contrib import messages
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView

from bds.autocomplete import bds_search
from bds.forms import ProfileForm, UserForm, UserFromClipperForm, UserFromScratchForm
from bds.mixins import MultipleFormView, StaffRequiredMixin
from shared.views import AutocompleteView

User = get_user_model()


class BDSAutocompleteView(StaffRequiredMixin, AutocompleteView):
    template_name = "bds/search_results.html"
    search_composer = bds_search


class Home(StaffRequiredMixin, TemplateView):
    template_name = "bds/home.html"


class UserUpdateView(StaffRequiredMixin, MultipleFormView):
    template_name = "bds/user_update.html"

    form_classes = {
        "user": UserForm,
        "profile": ProfileForm,
    }

    def dispatch(self, request, *args, **kwargs):
        self.user = get_object_or_404(User, pk=self.kwargs["pk"])
        return super().dispatch(request, *args, **kwargs)

    def get_user_instance(self):
        return self.user

    def get_profile_instance(self):
        return getattr(self.user, "bds", None)

    def get_success_url(self):
        return reverse("bds:user.update", args=(self.user.pk,))

    def form_valid(self, forms):
        user = forms["user"].save()
        profile = forms["profile"].save(commit=False)
        profile.user = user
        profile.save()
        messages.success(self.request, _("Profil mis à jour avec succès !"))

        return super().form_valid(forms)

    def form_invalid(self, forms):
        messages.error(self.request, _("Veuillez corriger les erreurs ci-dessous"))
        return super().form_invalid(forms)


class UserCreateView(StaffRequiredMixin, MultipleFormView):
    template_name = "bds/user_create.html"

    def get_form_classes(self):
        profile_class = ProfileForm

        if "clipper" in self.kwargs:
            user_class = UserFromClipperForm
        else:
            user_class = UserFromScratchForm

        return {"user": user_class, "profile": profile_class}

    def get_user_initial(self):
        if "clipper" in self.kwargs:
            clipper = self.kwargs["clipper"]
            email = "{}@clipper.ens.fr".format(clipper)
            fullname = self.request.GET.get("fullname", None)

            if fullname:
                # Heuristique : le premier mot est le prénom
                first_name = fullname.split()[0]
                last_name = " ".join(fullname.split()[1:])
            else:
                first_name = ""
                last_name = ""

            return dict(
                username=clipper,
                email=email,
                first_name=first_name,
                last_name=last_name,
            )
        else:
            return {}

    def get_success_url(self):
        return reverse("bds:user.update", args=(self.user.pk,))

    def form_valid(self, forms):
        # On redéfinit self.user pour get_success_url
        self.user = forms["user"].save()
        profile = forms["profile"].save(commit=False)
        profile.user = self.user
        profile.save()
        messages.success(self.request, _("Profil créé avec succès !"))

        return super().form_valid(forms)

    def form_invalid(self, forms):
        messages.error(self.request, _("Veuillez corriger les erreurs ci-dessous"))
        return super().form_invalid(forms)
