"""Base serializers for parking lot api"""

# Audit Log
from auditlog.models import LogEntry

# Django
from django.contrib.contenttypes.models import ContentType

# Django
from django.utils.translation import gettext_lazy as _
from drf_spectacular.utils import inline_serializer

# DRF
from rest_framework import serializers

CREATE = 0
UPDATE = 1
DELETE = 2
choices = {
    CREATE: _("Added"),
    UPDATE: _("Changed"),
    DELETE: _("Deleted"),
}


class LogEntrySerializer(serializers.ModelSerializer):
    """Log entry Model serializer"""

    message = serializers.SerializerMethodField()
    actor = serializers.CharField(source="actor.username", required=False)

    class Meta:
        model = LogEntry
        fields = ["action", "timestamp", "message", "actor"]

    def get_message(self, obj):
        """Return message"""
        action = choices[obj.action]

        if obj.action == CREATE:
            return f"{action}"
        changes = ", ".join([str(_(key)) for key in obj.changes.keys()])

        return f"{action}: {changes}"


def create_confirmation_serializer(name, additional_fields=None):
    fields = {"message": serializers.CharField()}
    if additional_fields:
        fields.update(additional_fields)
    return inline_serializer(name=name, fields=fields)


# Basic confirmation serializer
confirmation_inline_serializer = create_confirmation_serializer(
    "ConfirmationSerializer"
)

# Ticket confirmation serializer
ticket_confirmation_inline_serializer = create_confirmation_serializer(
    "TicketConfirmationSerializer", {"ticket_id": serializers.UUIDField()}
)

# Ticket exit confirmation serializer
ticket_exit_confirmation_inline_serializer = create_confirmation_serializer(
    "TicketExitConfirmationSerializer",
    {"ticket_id": serializers.UUIDField(), "exit_time": serializers.DateTimeField()},
)


class TranslatedSerializerField(serializers.Field):
    def to_representation(self, value):
        return _(value)


class ContentTypeModelSerializer(serializers.ModelSerializer):
    """Content type Model serializer"""

    name = TranslatedSerializerField()

    class Meta:
        model = ContentType
        fields = ["id", "name"]
