from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import IntegrityError

from core.forms import MessageForm
from core.models import Message
from core.util import logs
from mixins.views import AbortSave, ObjectCreate, ObjectDelete, ObjectList, ObjectUpdate

log = logs.get_logger(__name__)


class MessagePermissionMixin:
    def set_extra_args(self, user):
        self.extra_permission_args = {
            "session__user": user,
            "session__pk": self.kwargs["session"],
        }


class MessageList(LoginRequiredMixin, MessagePermissionMixin, ObjectList):
    list_template = "partials/message-list.html"
    model = Message
    page_title = "Messages"

    list_url_name = "messages"
    list_url_args = ["type", "session"]

    submit_url_name = "message_create"
    submit_url_args = ["type", "session"]


class MessageCreate(LoginRequiredMixin, MessagePermissionMixin, ObjectCreate):
    model = Message
    form_class = MessageForm

    submit_url_name = "message_create"
    submit_url_args = ["type", "session"]

    def form_valid(self, form):
        """If the form is invalid, render the invalid form."""
        try:
            return super().form_valid(form)
        except IntegrityError as e:
            if "UNIQUE constraint failed" in str(e):
                form.add_error("message", "Identifier rule already exists")
                return self.form_invalid(form)
            else:
                raise e

    def pre_save_mutate(self, user, obj):
        try:
            session = Message.objects.get(pk=self.kwargs["session"], user=user)
            obj.session = session
        except Message.DoesNotExist:
            log.error(f"Session {self.kwargs['session']} does not exist")
            raise AbortSave("session does not exist or you don't have access")


class MessageUpdate(LoginRequiredMixin, MessagePermissionMixin, ObjectUpdate):
    model = Message
    form_class = MessageForm

    submit_url_name = "message_update"
    submit_url_args = ["type", "pk", "session"]


class MessageDelete(LoginRequiredMixin, MessagePermissionMixin, ObjectDelete):
    model = Message
