from rest_framework import serializers

from apps.master import models as master_model
from base.serializers import DynamicFieldsModelSerializer


class AmenitiesUploadCSVSerializers(DynamicFieldsModelSerializer):
    """
    This is the AmenitiesCSVUploadSerializers.

    It serializes amenities data from a CSV file.

    Meta:
        model (AmenitiesMaster): The model used for serialization.
        fields (str): The fields to include in the serialization (all fields are included).
    """

    class Meta:
        model = master_model.AmenitiesMaster
        fields = ["name", "type_id"]

    def create(self, validated_data):
        type_id = validated_data.get("type_id")

        if type_id:
            amenity, created = master_model.AmenitiesMaster.objects.get_or_create(
                type_id=type_id, defaults=validated_data
            )

            if not created:
                # Update the existing amenities with new data
                for key, value in validated_data.items():
                    setattr(amenity, key, value)
                amenity.save()

            return amenity
        else:
            raise serializers.ValidationError(
                f"Type Id is required for update or creation."
            )


class ConnectorCSVUploadSerializers(DynamicFieldsModelSerializer):
    """
    This is the ConnectorCSVUploadSerializers.

    It serializes connector data from a CSV file.

    Meta:
        model (ConnectorMaster): The model used for serialization.
        fields (str): The fields to include in the serialization (all fields are included).
    """

    class Meta:
        model = master_model.ConnectorMaster
        fields = "__all__"

    def create(self, validated_data):
        type_id = validated_data.get("type_id")

        if type_id:
            station, created = master_model.ConnectorMaster.objects.get_or_create(
                type_id=type_id, defaults=validated_data
            )

            if not created:
                # Update the existing connector with new data
                for key, value in validated_data.items():
                    setattr(station, key, value)
                station.save()

            return station
        else:
            raise serializers.ValidationError(
                "Type Id is required for update or creation."
            )


class LocationsCSVUploadSerializers(DynamicFieldsModelSerializer):
    """
    This is the LocationsCSVUploadSerializers class responsible for serializing and deserializing location data.

    It allows users to manage the upload of location data from a CSV file and the creation or update of location records.

    Meta:
        model (LocationMaster): The model used for serialization and deserialization.
        fields (str): The fields to include in the serialization (all fields are included).
    """

    class Meta:
        model = master_model.LocationMaster
        fields = "__all__"

    def create(self, validated_data):
        """
        Create or update a location record based on the 'type_id' field.

        Args:
            validated_data (dict): Validated data containing location details.

        Returns:
            LocationMaster: The created or updated location record.
        """

        type_id = validated_data.get("type_id")

        if type_id:
            station, created = master_model.LocationMaster.objects.get_or_create(
                type_id=type_id, defaults=validated_data
            )

            if not created:
                # Update the existing location with new data
                for key, value in validated_data.items():
                    setattr(station, key, value)
                station.save()

            return station
        else:
            raise serializers.ValidationError(
                "Type Id is required for update or creation."
            )


class NetworkOperatorUploadCSVSerializers(DynamicFieldsModelSerializer):
    """
    This serializer is used for creating or updating network operator records from CSV data.

    Attributes:
        class Meta: Specifies the model and fields to include in the serialization.

    Methods:
        create(validated_data): Create or update a network operator record based on the 'type_id' field.
    """

    class Meta:
        model = master_model.NetworkOperatorMaster
        fields = "__all__"

    def create(self, validated_data):
        """
        Create or update a network operator record based on the 'type_id' field.

        Args:
            validated_data (dict): Validated data containing network operator details.

        Returns:
            NetworkOperatorMaster: The created or updated network operator record.

        Raises:
            serializers.ValidationError: If 'type_id' is missing in the input data.
        """
        type_id = validated_data.get("type_id")

        if type_id:
            # Attempt to get an existing network operator or create a new one based on 'type_id'
            (
                networkOperator,
                created,
            ) = master_model.NetworkOperatorMaster.objects.get_or_create(
                type_id=type_id, defaults=validated_data
            )

            if not created:
                # Update the existing network operator with new dat
                for key, value in validated_data.items():
                    setattr(networkOperator, key, value)
                networkOperator.save()

            return networkOperator
        else:
            raise serializers.ValidationError(
                "Type Id is required for update or creation."
            )
