from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse_lazy
from django.utils.safestring import mark_safe
from django.views.generic import (CreateView, DeleteView, TemplateView,
                                  UpdateView)

from gestion.mixins import ChefInstruRequiredMixin, ChefRequiredMixin
from gestion.models import Photo
from instruments.forms import ChefEditInstrumentForm, ChefReparationForm
from instruments.models import Instrument, Reparation


class ListeInstru(LoginRequiredMixin, TemplateView):
    template_name = "instruments/instru_liste.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["photo"] = Photo.objects.filter(cat="instru").order_by("?").first()
        context["instrus_dispo"] = (
            Instrument.objects.all().order_by("type").filter(statut="Disponible")
        )
        context["instrus_prete"] = (
            Instrument.objects.all().order_by("type").filter(statut="Prêté")
        )
        return context


class CreateInstru(ChefInstruRequiredMixin, CreateView):
    model = Instrument
    fields = [
        "owner",
        "user",
        "etat",
        "type",
        "marque",
        "model",
        "serial",
        "annee",
        "prix",
    ]
    template_name = "instruments/create_instru.html"
    success_url = reverse_lazy("instruments:liste")


class CreateRep(ChefInstruRequiredMixin, TemplateView):
    form_class = ChefReparationForm
    template_name = "instruments/create_rep.html"

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

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)

        if form.is_valid():
            rep = form.save(commit=False)
            rep.instru = get_object_or_404(Instrument, id=self.kwargs["pk"])
            rep.save()
            return redirect("instruments:fiche_instru", pk=self.kwargs["pk"])
        else:
            context = self.get_context_data()
            context["form"] = form
            return render(request, self.template_name, context)


class DeleteRep(ChefInstruRequiredMixin, TemplateView):
    model = Reparation
    template_name = "instruments/delete_instru.html"

    def get(self, request, *args, **kwargs):

        rep = get_object_or_404(self.model, id=self.kwargs["pk"])
        id_instru = rep.instru.id
        rep.delete()
        return redirect("instruments:fiche_instru", pk=id_instru)


class FicheInstru(LoginRequiredMixin, TemplateView):

    template_name = "instruments/update_instru.html"
    model = Instrument

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        instru = get_object_or_404(self.model, id=self.kwargs["pk"])
        reparations = Reparation.objects.filter(instru=self.kwargs["pk"]).order_by(
            "-date"
        )

        form = ChefEditInstrumentForm(instance=instru)
        infos = mark_safe(instru.infos)
        infos_en = mark_safe(instru.infos_en)

        context["reparations"] = reparations
        context["instru"] = instru
        context["form"] = form
        context["infos"] = infos
        context["infos_en"] = infos_en
        return context

    def post(self, request, *args, **kwargs):
        instru = get_object_or_404(self.model, id=self.kwargs["pk"])
        form = ChefEditInstrumentForm(request.POST, instance=instru)
        if request.user.profile.is_chef:
            if form.is_valid():
                form.save()
        context = self.get_context_data()
        context["form"] = form
        return render(request, self.template_name, context)


class UpdateRep(ChefInstruRequiredMixin, UpdateView):
    model = Reparation
    fields = ["date", "description", "description_en", "prix", "lieux"]
    template_name = "instruments/update_rep.html"

    def get_success_url(self):
        id_instru = get_object_or_404(Reparation, id=self.kwargs["pk"]).instru.id
        return reverse_lazy("instruments:fiche_instru", kwargs={"pk": id_instru})


class DeleteInstru(ChefInstruRequiredMixin, DeleteView):
    model = Instrument
    template_name = "instruments/delete_instru.html"
    success_url = reverse_lazy("instruments:liste")
