o
    did                     @   s  d dl Z d dl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 d dlmZmZmZ 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 d dl m!Z!m"Z" d dl#m$Z$ d dl%m&Z&m'Z' d dl(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)Z0G dd de)Z1G dd  d e)Z2G d!d" d"eZ3G d#d$ d$e)Z4dS )%    N)geosstatus)action)CreateAPIViewRetrieveAPIView)MultiPartParser)IsAuthenticatedIsAdminUserAllowAny)Response)APIView)models)upload_station_csv_data)StationListFilterStationMediaListFilter)station_serializers)station_servicesstation_list_services)CustomPagination)AdminOrPostOnlyPermissionIsAdminToAllowCRUD)BaseModelViewSet)settingsc                   @   s*   e Zd ZdZefZefZej	Z
dd ZdS )StationCSVUploadViewa  
    This is the StationCSVUploadView.

    It handles the CSV file upload for station data.

    Attributes:
        parser_classes (tuple): The parsers used for request data (MultiPartParser for handling file uploads).
        permission_classes (tuple): Permissions required to access this view (IsAuthenticated for authenticated users).

    Methods:
        post(request, *args, **kwargs): Handles the processing of uploaded CSV data.
    c                    sJ  |j d}|stdditjdS |jds tdditjdS t|}t	|j
 g d}t fdd	|D r|d
 tj|d
< |d tj|d< |d tj|d< |jddd g }| D ] \}}	t|	}
|
d |
d d|
d< |
d p|d|
d< ||
 qdt||jj tdditjdS tddd| ditjdS )a  
        Handles the processing of uploaded CSV data.

        Args:
            request (HttpRequest): The HTTP request containing the uploaded CSV file.
            *args: Variable-length argument list.
            **kwargs: Variable-length keyword argument list.

        Returns:
            Response: The response message indicating whether the stations were uploaded successfully.
        filemessagezFile not providedr   z.csvzInvalid file format)scarp_idnameaddressdescriptiontitle_descriptionmeta_descriptionphone	is_activeis_24_hours_openis_parking_freecost_descriptionlatitude	longitude	amenities
connectorsphotosc                 3   s    | ]}| v V  qd S N ).0colcolumnsr.   \/var/www/html/evchargy.com/django-station-ev/station_ev/apps/station/views/stations_views.py	<genexpr>`   s    z,StationCSVUploadView.post.<locals>.<genexpr>r+   r*   r,    T)valueZinplacer(   r)   )r(   r)   coordinatesr'   Nparking_cost_descriptionzStations uploaded successfullyzFile must have z, z columns)FILESgetr   r   HTTP_400_BAD_REQUESTr   endswithpdZread_csvlistr2   allapplyastliteral_evalZfillnaZiterrowsdictappendr   useridHTTP_200_OKjoin)selfrequestargskwargsr   dfZrequired_columnsZ	json_data_rowrow_datar.   r1   r3   post/   sF   





zStationCSVUploadView.postN)__name__
__module____qualname____doc__r   parser_classesr	   permission_classesr   ZStationCSVUploadSerializersserializer_classrQ   r.   r.   r.   r3   r      s    r   c                   @   s   e Zd ZdZefZejZe	j
j ZeZddgZg dZdd Zdd Zd	d
 ZeddgdegddddZeddgdegddddZdS )StationModelViewSeta  
    This is the StationModelViewSet class responsible for managing station data.

    It provides endpoints for creating, retrieving, updating, and deleting station records.

    Attributes:
        permission_classes (tuple): Specifies the permissions required to access this view. It's set to IsAuthenticated,
                                   allowing only authenticated users to interact with station records.
        serializer_class (station_serializers.StationMasterSerializer): The serializer class used to serialize
        and deserialize station data.
        filter_backends (list): A list of filter backends to use for filtering station data.
        queryset (QuerySet): The queryset of station records that this viewset operates on.
        filterset_class (StationListFilter): The filterset class used to filter station data.
        search_fields (list): A list of fields to search for when filtering.
        http_method_names (list): A list of the HTTP methods that this viewset supports.

    Methods:
        get(request, *args, **kwargs): Retrieves station data based on the request parameters.
        delete(request, *args, **kwargs): Deletes a specific station record.
        list(request, *args, **kwargs): Retrieves a list of station data based on the request parameters.
        partial_update(request, *args, **kwargs): Handles partial updates (not allowed, returns an error).
        destroy(request, *args, **kwargs): Handles the destruction of station records (not allowed, returns an error).
        delete(request, pk=None): Deletes a specific station record based on the provided primary key.
        station_update(request, pk=None): Updates a specific station record based on the provided primary key.
    r   r   r:   deletepatchc           	      C   s   | j  jdd}| jjdvr| j jdd}| jjd}| jjd}|r(|s*|S z%tt|	d\}}tt|	d\}}t
j||||f}|j|d	W S  tyZ   | Y S w )
a/  
        Get the queryset of station records based on geographic coordinates.

        This method filters station records based on a bounding box defined by
        top-right and bottom-left lat/lng coordinates.

        Returns:
            QuerySet: The filtered queryset of station records.
        Fis_rejected)DELETETis_verifiedtop_right_latlngbottom_left_latlng,)Zcoordinates__coveredby)querysetannotate_is_rejected_stationfilterrJ   methodGETr:   mapfloatsplitr   Polygon	from_bbox
ValueError)	rI   re   rb   rc   Ztop_right_latZtop_right_lngZbottom_left_latZbottom_left_lngZbounding_boxr.   r.   r3   get_queryset   s&   


z StationModelViewSet.get_querysetc                 O   s    g d}t j| |d}t|jS )as  
        Retrieve a paginated list of station data based on request parameters.

        Args:
            request (HttpRequest): The HTTP request object.
            *args: Variable-length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Response: A paginated response containing a list of serialized station data.
        )rF   r   r    r   r7   r+   	open_time
close_timer%   bookmarkratingassetsslugfieldsr   get_paginated_responser   data)rI   rJ   rK   rL   rx   
serializerr.   r.   r3   r>      s   
zStationModelViewSet.listc                 O   s>   |   }tj||jdd}|jdd |  t|jtjdS )Z  
        Partially update a station record based on the provided data.

        Args:
            request (HttpRequest): The HTTP request object.
            *args: Variable-length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Response: The serialized data of the updated station record.
        Tr{   partialraise_exceptionr   )	
get_objectr   #StationCreateUpdateMasterSerializerr{   is_validsaver   r   rG   rI   rJ   rK   rL   stationr|   r.   r.   r3   partial_update   s   z"StationModelViewSet.partial_updateFr:   admin)detailmethodsurl_pathrW   Nc                 C       g d}t j| |d}t|jS )a5  
        Retrieve a paginated list of station data for admin purposes.

        Args:
            request (HttpRequest): The HTTP request object.
            pk: current object id, default null

        Returns:
            Response: A paginated response containing a list of serialized station data.
        )rF   r   r   Zall_network_operatorsrt   ru   rv   rw   ry   rI   rJ   pkrx   r|   r.   r.   r3   get_admin_station_list   s   	
z*StationModelViewSet.get_admin_station_listzmap-pinsc                 C   r   )a/  
        Retrieve a paginated list of station data for map pins.

        Args:
            request (HttpRequest): The HTTP request object.
            pk: current object id, default null

        Returns:
            Response: A paginated response containing a list of serialized station data.
        )rF   r   r   r7   rv   rw   ry   r   r.   r.   r3   get_map_pins  s   
z StationModelViewSet.get_map_pinsr-   )rR   rS   rT   rU   r   rW   r   StationMasterSerializerrX   station_modelStationMasterobjectsr?   re   r   filterset_classsearch_fieldshttp_method_namesrp   r>   r   r   r
   r   r   r   r.   r.   r.   r3   rY      s2    #rY   c                   @   s,   e Zd ZdZefZejZe	j
j ZdZdS )StationRetrieveAPIViewz
    A view for retrieving details of a specific StationMaster object.

    This view allows retrieval of StationMaster objects by their slug field.
    It does not require authentication and can be accessed by any user (AllowAny permission).
    rv   N)rR   rS   rT   rU   r   rW   r   r   rX   r   r   r   r?   re   lookup_fieldr.   r.   r.   r3   r   4  s    r   c                   @   s.   e Zd ZdZefZejZe	j
j ZdgZdS )StationCreateUpdateModelViewSeta  
    This is the StationCreateUpdateModelViewSet class responsible for handling CSV file uploads for station data.

    It provides endpoints for uploading and updating station data from CSV files.

    Attributes:
        permission_classes (tuple): Specifies the permissions required to access this view. It's set to IsAuthenticated,
                                   allowing only authenticated users to use this view.
    rQ   N)rR   rS   rT   rU   r	   rW   r   r   rX   r   r   r   r?   re   r   r.   r.   r.   r3   r   B  s    

r   c                   @   sB   e Zd ZdZeefZejZ	e
jj ZddgZdd Zdd ZdS )	StationVerificationModelViewSeta+  
    This view handles the verification and update of station data from CSV file uploads.

    This view is responsible for managing the uploading and updating of station data from CSV files,
    specifically for the purpose of station verification.

    Attributes:
        permission_classes (tuple): Specifies the permissions required to access this view.
        It's set to (IsAuthenticated, IsAdminUser), allowing only authenticated and admin users to use this view.
        serializer_class (StationVerificationSerializer): The serializer used to validate and process station data.
        queryset (QuerySet): The initial queryset of station records that this viewset operates on.
        http_method_names (list): A list of the HTTP methods that this viewset supports, including 'GET' and 'PATCH'.
    r:   r\   c                 C   s   | j jdd jddS )a9  
        Get the queryset of unverified station records.

        This method filters station records based on the 'is_verified' field, returning
        only those that are not yet verified (is_verified=False).

        Returns:
            QuerySet: The filtered queryset of unverified station records.
        Fr`   r]   )re   rg   rf   )rI   r.   r.   r3   rp   g  s
   z,StationVerificationModelViewSet.get_querysetc                 O   sV   |   }| j||jdd}|jdd |  tjjj|dj	dd t
|jtjdS )r}   Tr~   r   r   r`   r   )r   get_serializerr{   r   r   r   StationMediar   rg   updater   r   rG   r   r.   r.   r3   r   x  s   z.StationVerificationModelViewSet.partial_updateN)rR   rS   rT   rU   r	   r
   rW   r   ZStationVerificationSerializerrX   r   r   r   r?   re   r   rp   r   r.   r.   r.   r3   r   S  s    r   c                   @   sF   e Zd ZdZeefZejZ	e
jj ZeZg dZdd Zdd ZdS )StationMediaViewSetak  
    This is the StationMediaViewSet class responsible for managing station media assets, such as images or files.

    It provides endpoints for uploading and deleting media assets associated with station records.

    Attributes:
        permission_classes (tuple): Specifies the permissions required to access this view. It's set to IsAuthenticated,
                                   allowing only authenticated users to use this view.
        parser_classes (tuple): The parsers used for request data, which includes MultiPartParser for handling file uploads.
        serializer_class (UploadStationMediaSerializer): The serializer class used for deserializing and handling media asset data.
        queryset (QuerySet): The queryset for accessing station media records.
        http_method_names (list): Specifies the supported HTTP methods for this view, including 'post' and 'delete'.

    Methods:
        create(request, *args, **kwargs): Handles the uploading of station media assets and associates them with a specific station.
        delete(request, *args, **kwargs): Handles the removal of station media assets.
    )r:   rQ   r\   r[   c                 C   s   | j d}| jj|dS )a*  
        Get the queryset of objects filtered by the associated station.

        This method retrieves the value of 'station_id' from the URL kwargs
        and filters the queryset based on the associated station.

        Returns:
            QuerySet: The filtered queryset of objects.
        
station_idr   )rL   r:   re   rg   )rI   r   r.   r.   r3   rp     s   
z StationMediaViewSet.get_querysetc              	   O   s  | j d}t|}|stdditjdS g }t|jD ]\}}|	|jd| d|j
d| dd q|sEtdd	itjdS |jjsftjjj|j|d
}	|	 t| dkrftdditjdS | j|dd|id}
|
 r|
j||jtjd t|
j
tjdS t|
jtjdS )a  
        Handles the uploading of station media assets and associates them with a specific station.

        Args:
            request (HttpRequest): The HTTP request object containing media assets and associated data.
            *args: Variable-length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Response: A response indicating the success or failure of the media asset upload operation.

        This method processes the uploaded media assets, associates them with a specified station, and handles the creation
        of station media records. It verifies the provided station ID, asset data, and the associated user.
        r   r   zInvalid station IDr   zasset[]zasset_type[)asset
asset_typezAssets are required)rE   r      zYou can upload up-to 5 imagesTrJ   )r{   manycontext)r   rE   ra   )rL   r:   r   Zget_station_by_idr   r   r;   	enumerater9   rD   r{   rE   is_superuserr   r   r   rg   countlenr   r   r   r   ALLOW_AUTO_VERIFY_MEDIAHTTP_201_CREATEDerrors)rI   rJ   rK   rL   r   r   ru   indexr   station_mediar|   r.   r.   r3   create  sZ   

zStationMediaViewSet.createN)rR   rS   rT   rU   r	   r   rW   r   ZUploadStationMediaSerializerrX   r   r   r   r?   re   r   r   r   rp   r   r.   r.   r.   r3   r     s    r   c                   @   s2   e Zd ZdZeefZejZ	e
jj Zg dZdS )StationConnectorViewSeta  
    A viewset for handling StationConnectors.

    This viewset allows CRUD operations (Create, Read, Update, Delete) for StationConnectors.
    It requires authentication and admin user permissions for access.

    Attributes:
        permission_classes (tuple): Permissions required to access this view.
        serializer_class: Serializer class for handling StationConnectors.
        queryset: The queryset containing all StationConnectors.
        http_method_names (list): The allowed HTTP methods for this viewset.
    )rQ   r[   r\   N)rR   rS   rT   rU   r	   r
   rW   r   ZStationConnectorSerializerrX   r   StationConnectorsr   r?   re   r   r.   r.   r.   r3   r     s    r   c                   @   s.   e Zd ZdZefZeZej	Z
dgZdd ZdS )StationPhotoAPIViewa  
    API view to get a combined list of station media and rating media assets with pagination.

    Attributes:
        permission_classes (tuple): Permissions required to access this view (IsAuthenticated for authenticated users).
        pagination_class (CustomPagination): The custom pagination class for paginating the combined assets.
        serializer_class (CombinedAssetSerializer): The serializer used for serializing the combined assets.
        http_method_names (list): The allowed HTTP methods, in this case, only GET is allowed.

    Methods:
        get(request, *args, **kwargs): Retrieve the combined assets for a specific station based on the station ID.
    r:   c                 O   s   | d}tjjj|ddddd}tjjj|ddddd}||}|D ]}tj	 |d  |d< q(t
 }	|	||}
| j|
dd|id	}|	|jS )
ak  
        Retrieve the combined assets for a specific station based on the station ID.

        Args:
            request (HttpRequest): The HTTP request object.
            *args: Variable-length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Response: A paginated response containing the combined assets.
        r   T)Zstation__idra   r   r   rF   )Zrating_station__station__idra   rJ   )r   r   )r:   r   r   r   rg   valuesStationRatingMediaunionr   	MEDIA_URLr   paginate_querysetrX   rz   r{   )rI   rJ   rK   rL   r   Zstation_media_assetsZstation_rating_media_assetsZcombined_assetsZ
asset_info
paginationZresult_pageserializersr.   r.   r3   r:   %  s,   




zStationPhotoAPIView.getN)rR   rS   rT   rU   r   rW   r   pagination_classr   ZCombinedStationAssetSerializerrX   r   r:   r.   r.   r.   r3   r     s    r   c                   @   sf   e Zd ZdZeefZejZ	e
jj ZeZg dZeddgdddd Zeddgd	dd
d ZdS )UnverifiedStationMediaViewSetaF  
    This viewset provides endpoints to manage unverified station media.

    Attributes:
        permission_classes (tuple): Specifies the permissions required to access this view.
        serializer_class: The serializer class used for handling station media data.
        queryset (QuerySet): The queryset for accessing unverified station media records.
        filterset_class: The filterset class used for filtering station media records.
        http_method_names (list): Specifies the supported HTTP methods for this view,
        including 'get', 'delete', and 'patch'.
    rZ   Fr[   )r   r   r   c              
   O   s|   |j dg }ztjjj|d \}}td| ditj	dW S  t
y= } ztdt|itjdW  Y d}~S d}~ww )aY  
        Delete selected unverified media.

        Args:
            request (HttpRequest): The HTTP request object.
            *args: Variable-length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Response: A response indicating the success or failure of the media deletion operation.
        	media_idsZid__inr   z media deleted successfullyr   errorN)r{   r:   r   r   r   rg   r[   r   r   HTTP_204_NO_CONTENT	ExceptionstrHTTP_500_INTERNAL_SERVER_ERROR)rI   rJ   rK   rL   r   Zdeleted_countrN   er.   r.   r3   delete_selected_mediad  "   z3UnverifiedStationMediaViewSet.delete_selected_mediar\   Zverifiedc              
   O   s|   |j dg }ztjjj|djdd}td| ditj	dW S  t
y= } ztdt|itjdW  Y d	}~S d	}~ww )
a]  
        Verify selected unverified media.

        Args:
            request (HttpRequest): The HTTP request object.
            *args: Variable-length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Response: A response indicating the success or failure of the media verification operation.
        r   r   Tr`   r   z media verified successfullyr   r   N)r{   r:   r   r   r   rg   r   r   r   rG   r   r   r   )rI   rJ   rK   rL   r   updated_countr   r.   r.   r3   verify_selected_media  r   z3UnverifiedStationMediaViewSet.verify_selected_mediaN)rR   rS   rT   rU   r	   r
   rW   r   ZStationMediaSerializerrX   r   r   r   r?   re   r   r   r   r   r   r   r.   r.   r.   r3   r   Q  s    
r   )5rA   Zpandasr=   django.contrib.gisr   rest_frameworkr   rest_framework.decoratorsr   Zrest_framework.genericsr   r   Zrest_framework.parsersr   Zrest_framework.permissionsr	   r
   r   rest_framework.responser   rest_framework.viewsr   Zapps.stationr   r   Z6apps.station.background_tasks.upload_station_csv_tasksr   Z$apps.station.filters.station_filtersr   r   Zapps.station.serializersr   Zapps.station.servicesr   r   Zbase.paginatorr   base.permissionsr   r   
base.viewsr   
station_evr   r   rY   r   r   r   r   r   r   r   r.   r.   r.   r3   <module>   s:    g 1=n?