from apps.station import models
from apps.station.serializers.station_serializers import StationMasterSerializer
from base.serializers import DynamicFieldsModelSerializer


class StationBookmarkSerializer(DynamicFieldsModelSerializer):
    """
    This is the StationBookmarkSerializer class responsible for serializing and deserializing bookmarked station data.

    It enables users to manage the serialization and deserialization of bookmarked station data,
    allowing for efficient processing of data related to bookmarked stations.

    Meta:
        model (BookmarkStation): The model used for serialization and deserialization.
        fields (tuple): Specifies the fields included in the serialization and deserialization process.
        read_only_fields (tuple): Fields that are marked as read-only.
        extra_kwargs (dict): Additional configurations for specific fields.

    Methods:
        create(validated_data): Creates a new station bookmark and associates it with the requesting user.
    """

    station_data = StationMasterSerializer(source="station", read_only=True)

    class Meta:
        model = models.BookmarkStation
        fields = ("id", "station", "user", "station_data")
        read_only_fields = ("id", "user")
        extra_kwargs = {
            "station": {"write_only": True},
        }

    def create(self, validated_data):
        """
        Create a new station bookmark and associate it with the requesting user.

        Args:
        validated_data (dict): The validated data for creating a new station bookmark.

        Returns:
        BookmarkStation: The created station bookmark.

        This method associates the created station bookmark with the requesting user.
        """
        station_id = validated_data.pop("station", [])
        request = self.context.get("request")

        station, create = models.BookmarkStation.objects.get_or_create(
            station=station_id, user=request.user
        )
        return station
