o
    dilc                     @   s<  d dl mZ d dlmZ d dlmZ d dlmZ d dlm	Z	m
Z
 d dlmZmZmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZmZ d dlmZ G dd deZG dd deZG dd deZG dd deZG dd deZ G dd deZ!G dd deZ"G dd deZ#G dd deZ$G dd deZ%d S )!    )AnonymousUser)Avg)
PointField)serializers)AmenitiesMasterLocationMaster)AmenitiesMasterSerializersConnectorMasterSerializersLocationMasterSerializers)models)station_services)get_or_create_connectorget_or_create_network_operator)DynamicFieldsModelSerializerDynamicFieldsSerializer)settingsc                   @      e Zd ZdZG dd dZdS )StationMediaSerializera  
    This is the StationMediaSerializer.

    It serializes station medias data from a CSV file.

    Meta:
        model (StationMedia): The model used for serialization.
        fields (str): The fields to include in the serialization (all fields are included).
    c                   @      e Zd ZejZdZdZdS )zStationMediaSerializer.Metaidasset
asset_typeis_verifiedstationN__name__
__module____qualname__station_modelStationMediamodelfieldsread_only_fields r%   r%   g/var/www/html/evchargy.com/django-station-ev/station_ev/apps/station/serializers/station_serializers.pyMeta!       r'   Nr   r   r   __doc__r'   r%   r%   r%   r&   r      s    
r   c                   @   s0   e Zd ZdZeddg ddZG dd dZdS )	StationConnectorSerializera  
    This is the StationConnectorSerializer.

    It serializes station connectors data from a CSV file.

    Meta:
        model (StationConnectors): The model used for serialization.
        fields (str): The fields to include in the serialization (all fields are included).
    	connectorT)r   name
short_nameimage)source	read_onlyr#   c                   @   s&   e Zd ZejZdZdZdddiiZdS )zStationConnectorSerializer.Meta)r   r   r,   	kilowattscost_descriptionnetwork_operatorconnector_datar   r   requiredFN)	r   r   r   r    StationConnectorsr"   r#   r$   extra_kwargsr%   r%   r%   r&   r'   6   s
    	r'   N)r   r   r   r*   r	   r5   r'   r%   r%   r%   r&   r+   '   s    

r+   c                   @   s,   e Zd ZdZeddgdZG dd dZdS )StationAmenitiesSerializera  
    This is the StationAmenitiesSerializer.

    It serializes station amenities data from model.

    Meta:
        model (StationAmenities): The model used for serialization.
        fields (str): The fields to include in the serialization (all fields are included).
    r   r-   )r#   c                   @   r   )zStationAmenitiesSerializer.Meta__all__r   N)r   r   r   r    StationAmenitiesr"   r#   r$   r%   r%   r%   r&   r'   R   r(   r'   N)r   r   r   r*   r   	amenitiesr'   r%   r%   r%   r&   r:   E   s    
r:   c                   @   s.   e Zd ZdZedddgdZG dd dZdS )	StationLocationsSerializera  
    This is the StationLocationsSerializer.

    It serializes station locations data from model.

    Meta:
        model (StationLocation): The model used for serialization.
        fields (str): The fields to include in the serialization (all fields are included).
    locationr   r-   )r0   r#   c                   @   r   )zStationLocationsSerializer.Metar;   r   N)r   r   r   r    StationLocationr"   r#   r$   r%   r%   r%   r&   r'   e   r(   r'   N)r   r   r   r*   r
   	locationsr'   r%   r%   r%   r&   r>   X   s    
r>   c                   @   sf   e Zd ZdZeje ddZeje ddZ	eje ddZ
eddZG dd dZdd	 Zd
S )StationCSVUploadSerializersa  
    This is the StationCSVUploadSerializers.

    It serializes station data from a CSV file.

    Attributes:
        coordinates (PointField): A GeoDjango PointField allowing the inclusion of location data.
        stations (SerializerMethodField): A dynamically generated field for retrieving and
        serializing station connectors.
        amenities (SerializerMethodField): A dynamically generated field for retrieving and
        serializing station amenities.


    Meta:
        model (StationMaster): The model used for serialization.
        fields (str): The fields to include in the serialization (all fields are included).
    T)child
write_onlyFr7   c                   @   s   e Zd ZejZg dZdS )z StationCSVUploadSerializers.Meta)scarp_idr-   addressdescriptiontitle_descriptionmeta_descriptionphone_number	is_activeis_24_hours_openis_parking_freeparking_cost_descriptioncoordinatesr=   
connectorsphotosN)r   r   r   r    StationMasterr"   r#   r%   r%   r%   r&   r'      s    r'   c              	   C   s  | j dd }|dg }|dg }|dg }g }|D ]}ztjj|d}|| W q tjy7   Y qw g }	|D ]C}
|
d}|
drNt|
d }|
dr|
d}|D ]$}i }|rf|j|d< nd |d< t	|}|j|d	< |d
 |d
< |	| qZq<|d}|rt
jjj|d }|r|S t||}t|| |	D ]}|j|d< qt|	dd}| r|  nt|jt||| |S td)Nuserr=   rQ   rR   )type_idmakeoutletsr4   r,   r2   rF   )rF   r   Tdatamanyz,scarp_id is required for update or creation.)contextgetpopr   objectsappendDoesNotExistr   r   r   r    rS   filterfirstr   handle_stationshandle_amenitiesr+   is_validsaver   ValidationErrorerrorsZhandle_station_media)selfvalidated_dataZrequest_useramenities_dataconnectors_dataZ
photo_dataZamenities_idsZamenities_type_idZamenityZconnector_data_listrQ   r4   rW   Zoutletconnector_dictr,   rF   r   station_connector_serializerr%   r%   r&   create   sl   






z"StationCSVUploadSerializers.createN)r   r   r   r*   r   	ListFieldIntegerFieldr=   	DictFieldrQ   rR   r   rP   r'   ro   r%   r%   r%   r&   rB   k   s    
rB   c                   @   s   e Zd ZdZeddZe Ze Z	e Z
ejg dZe Ze Zejdg dZejdg dZejdg dZG dd dZd	d
 Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )StationMasterSerializera  
    This is the StationMasterSerializer class responsible for serializing station data.

    It takes data from the StationMaster model and structures it for use in API responses.

    Attributes:
        coordinates (PointField): A GeoDjango PointField allowing the inclusion of location data.
        connectors (SerializerMethodField): A dynamically generated field for retrieving and
        serializing station connectors.
        amenities (SerializerMethodField): A dynamically generated field for retrieving and
        serializing station amenities.
        locations (SerializerMethodField): A dynamically generated field for retrieving and
        serializing station locations.

    Meta:
        model (StationMaster): The model used for serialization.
        fields (tuple): Specifies the fields to be included in the serialization. All fields are included,
                        including 'id', 'name', 'address', 'description', 'title_description', 'meta_description',
                        'phone_number', 'email', 'is_active', 'open_time', 'close_time', 'is_24_hours_open',
                        'is_parking_free', 'parking_cost_description', 'coordinates', and 'connectors'.

    Methods:
        get_connectors(obj): Retrieves and serializes the station connectors associated with the station.
        get_amenities(obj): Retrieves and serializes the station amenities associated with the station.
    FrE   )defaultT)r1   rt   c                   @   s   e Zd ZejZdZeZdS )zStationMasterSerializer.Meta)r   r-   rG   rH   rI   rJ   rK   emailwebsiterL   	open_time
close_timerM   rN   rO   rP   rQ   r=   rA   assetsratingbookmarkall_network_operatorsall_connectorsall_locationsslugNr   r   r   r    rS   r"   r#   r$   r%   r%   r%   r&   r'   
  s    r'   c                 C   s&   |j  }t|dg d| jd}|jS )NT)r   r2   r3   r5   r4   )rZ   r#   r[   )station_connectorsallr+   r[   rY   )ri   objrQ   Zconnectors_serializerr%   r%   r&   get_connectors*  s   
z&StationMasterSerializer.get_connectorsc                 C       |j  }t|ddgd}|jS )NTr=   rZ   r#   )station_amenitiesr   r:   rY   )ri   r   r=   Zamenities_serializerr%   r%   r&   get_amenities:  
   
z%StationMasterSerializer.get_amenitiesc                 C   r   )NTrA   r   )station_locationsr   r>   rY   )ri   r   rA   Zlocations_serializerr%   r%   r&   get_locationsA  r   z%StationMasterSerializer.get_locationsc                 C   \   |j  }t }g }|D ]}|jr+|jjd ur+|jj}||vr+|| ||jj q|S N)r   r   setr?   r-   r   addr_   )ri   r   rA   Zunique_locationresultr?   location_idr%   r%   r&   get_all_locationsH  s   

z)StationMasterSerializer.get_all_locationsc                 C   sp   |j j|ddddd}tjjj|ddddd}||}|D ]}| jd t	j
 |d  |d< q"|S )NT)r   r   r   r   r   )Zrating_station__stationr   request)station_mediasra   valuesr    StationRatingMediar^   unionr[   build_absolute_urir   	MEDIA_URL)ri   r   station_media_assetsstation_rating_media_assetscombined_assets
asset_infor%   r%   r&   
get_assetsW  s$   




z"StationMasterSerializer.get_assetsc                 C   s2   |j  }|j tdd }|t|pdddS )Nrz   Zrating__avgr      )total_countaverage_rating)station_ratingscount	aggregater   round)ri   r   r   r   r%   r%   r&   
get_ratingm  s
   
z"StationMasterSerializer.get_ratingc                 C   sD   | j dd }|r |jr t|jts tjjj||jd}|	 S dS )Nr   )r   rT   F)
r[   r\   rT   
isinstancer   r    BookmarkStationr^   ra   exists)ri   r   r   r{   r%   r%   r&   get_bookmarky  s   z$StationMasterSerializer.get_bookmarkc                 C   r   r   )r   r   r   r4   r-   r   r   r_   )ri   r   r   Zunique_network_operatorsr   r,   network_operator_idr%   r%   r&   get_all_network_operators  s   

z1StationMasterSerializer.get_all_network_operatorsc                 C   r   r   )r   r   r   r,   r.   r   r   r_   )ri   r   r   Zunique_connectorsr   r,   connector_idr%   r%   r&   get_all_connectors  s   

z*StationMasterSerializer.get_all_connectorsN)r   r   r   r*   r   rP   r   SerializerMethodFieldrQ   r=   rA   ry   rz   r{   r|   r}   r~   r'   r   r   r   r   r   r   r   r   r   r%   r%   r%   r&   rs      s0    
 rs   c                   @   sv   e Zd ZdZejej ddddZ	e
ddddZejej ddddZeddZG dd dZdd	 Zd
d ZdS )#StationCreateUpdateMasterSerializera$  
    This is the StationCreateUpdateMasterSerializer class responsible for serializing and deserializing station data
    when creating or updating station records.

    It handles both station details and associated amenities and connectors.

    Attributes:
        amenities (PrimaryKeyRelatedField): A field for specifying associated amenities related to the station.
        stations (StationConnectorSerializer): A field for specifying station connectors.
        locations (PrimaryKeyRelatedField): A field for specifying associated locations related to the station.
        coordinates (PointField): A GeoDjango PointField for specifying the station's geographical coordinates.

    Meta:
        model (StationMaster): 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 field-specific options and requirements.

    Methods:
        create(validated_data): Handles the creation of a new station record with associated amenities and connectors.
        update(instance, validated_data): Handles the update of an existing station record with associated amenities
        and connectors.
    T)querysetrZ   r7   rD   )rZ   r7   rD   rE   c                   @   s>   e Zd ZejZdZdZddiddiddiddiddidZdS )z(StationCreateUpdateMasterSerializer.Meta)r   r-   rG   is_owner_or_userrN   rO   rK   ru   rv   rH   rM   rw   rx   rL   r=   stationsrP   rA   r   )r   r   r7   T)r-   rG   r   rN   rL   N)	r   r   r   r    rS   r"   r#   r$   r9   r%   r%   r%   r&   r'     s    
r'   c                 C   s
  | dg }| dg }| dg }g }|D ](}|d}i }|r'|j|d< nd|d< |d j|d< |d|d< || q| jd}	t|d	krPtd
|	jj	rXd|d< t
j|d}
t
|
|	j t
|
| t
|
| t|dd}|jdd |j|
d |
S )a  
        Creates a new station record and manages associated amenities and connectors.

        Args:
            validated_data (dict): Validated data containing station details, amenities, connectors, and coordinates.

        Returns:
            StationMaster: The newly created station record.

        Raises:
            serializers.ValidationError: If the 'connectors' data is empty, indicating an incomplete station creation.
        ```
        r=   r   rA   r4   Nr,   r2   r   r   zStations can not be emptyTr   )rj   rX   )raise_exceptionr   )r]   r\   r   r_   r[   lenr   rg   rT   is_superuserr   rc   Zhandle_stations_userhandle_locationsrd   r+   re   rf   )ri   rj   rk   rl   locations_dataZconnectors_dict_datar,   r4   rm   r   r   rn   r%   r%   r&   ro     s8   

z*StationCreateUpdateMasterSerializer.createc                 C   sr   | dg }| dg }| dg }| D ]
\}}t||| q|  t|| t|| t|| |S )Nr=   r   rA   )r]   itemssetattrrf   r   r   rd   Zhandle_update_connectors)ri   instancerj   rk   rl   r   attrvaluer%   r%   r&   update*  s   z*StationCreateUpdateMasterSerializer.updateN)r   r   r   r*   r   PrimaryKeyRelatedFieldr   r^   r   r=   r+   r   r   rA   r   rP   r'   ro   r   r%   r%   r%   r&   r     s$     :r   c                   @   r   )UploadStationMediaSerializera  
    This is the UploadStationMediaSerializer class responsible for serializing and deserializing station media assets.

    It allows users to manage the upload of media assets, associating them with station records.

    Meta:
        model (StationMedia): 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.
    c                   @   r   )z!UploadStationMediaSerializer.Metar   r6   Nr   r%   r%   r%   r&   r'   I  r(   r'   Nr)   r%   r%   r%   r&   r   =  s    r   c                   @   s8   e Zd ZdZeddZe ZG dd dZ	dd Z
dS )	StationVerificationSerializera<  
    Serializer for verifying station details and media uploads.

    This serializer is responsible for serializing and deserializing station media assets
    for the purpose of verifying station information and uploading media files associated with stations.

    Attributes:
        coordinates (PointField): Represents the geographical coordinates of the station's location.
        It is a required field for verifying the station.

    Meta:
        model (StationMaster): Specifies the model used for serialization and deserialization,
        which in this case is 'StationMaster'.
        fields (tuple): Specifies the fields included in the serialization and deserialization process.
        These fields include 'id', 'name', 'address', 'description', 'phone_number', 'email',
        'website', 'is_active', 'open_time', 'close_time', 'is_24_hours_open', 'is_parking_free',
        'parking_cost_description', 'coordinates', and 'is_verified'.
        read_only_fields (tuple): Defines fields that are marked as read-only, and in this case,
        'id' is read-only.
    TrE   c                   @   r   )z"StationVerificationSerializer.Meta)r   r-   rG   rH   rK   ru   rv   rL   rw   rx   rM   rN   rO   rP   r   ry   r6   Nr   r%   r%   r%   r&   r'   j  s    r'   c                 C   sB   g }|j  D ]}||j| jd tj |j d q|S )Nr   )r   r   )	r   r   r_   r   r[   r   r   r   r   )ri   r   ry   Zstation_assetsr%   r%   r&   r     s   
	z(StationVerificationSerializer.get_assetsN)r   r   r   r*   r   rP   r   r   ry   r'   r   r%   r%   r%   r&   r   O  s    r   c                   @   s0   e Zd ZdZe Ze Ze Z	dd Z
dS )CombinedStationAssetSerializerad  
    Serializer for combining station media and rating media assets with additional information.

    Attributes:
        id (int): The identifier for the combined asset.
        asset (str): The full URL of the asset.
        asset_type (int): The type of the asset.

    Methods:
        get_asset(obj): Method to retrieve the full URL of the asset.
    c                 C   s(   | j d}|dr||d S dS )z
        Retrieve the full URL of the asset.

        Args:
            obj (dict): The dictionary representing the combined asset.

        Returns:
            str or None: The full URL of the asset or None if it's not available.
        r   r   N)r[   r\   r   )ri   r   r   r%   r%   r&   	get_asset  s   

z(CombinedStationAssetSerializer.get_assetN)r   r   r   r*   r   rq   r   r   r   r   r   r%   r%   r%   r&   r     s    r   N)&django.contrib.auth.modelsr   django.db.modelsr   Zdrf_extra_fields.geo_fieldsr   rest_frameworkr   Zapps.master.modelsr   r   *apps.master.serializers.master_serializersr   r	   r
   apps.stationr   r    apps.station.servicesr   Z&apps.station.services.station_servicesr   r   base.serializersr   r   
station_evr   r   r+   r:   r>   rB   rs   r   r   r   r   r%   r%   r%   r&   <module>   s.    v I C