import bleach

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.urls import reverse_lazy
from django.shortcuts import redirect
from django.views import View

from tickets.forms import TicketForm
from tickets.utils import UserCanReadTicketListMixin


class TicketCreateView(LoginRequiredMixin, UserCanReadTicketListMixin, View):
    def post(self, request, pk):
        form = TicketForm(request.user, request.POST)

        if form.is_valid():
            new_ticket = form.save(commit=False)
            new_ticket.created_by = request.user
            new_ticket.note = bleach.clean(form.cleaned_data["note"], strip=True)
            new_ticket.save()

            messages.success(self.request, f'The "{new_ticket.title}" ticket has been successfully created in {new_ticket.ticket_list.group} > {new_ticket.ticket_list}.')
        else:
            messages.error(self.request, "Failed to create the ticket.")

        return redirect(reverse_lazy('tickets:ticket_list_detail', kwargs={'pk': pk}))