o
    di?                     @   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 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 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Z$dS )    )settings)ObjectDoesNotExiststatus)CreateAPIView)AllowAnyIsAuthenticated)Response)APIView)
TokenError)RefreshToken)ProfileListFilter)UserUserCode)account_serializers)BaseModelViewSet)sending_email)send_fast2sms_otpc                   @   *   e Zd ZdZefZejZdgZ	dd Z
dS )LoginOrRegistrationViewa  
    This is the LoginOrRegistrationView.

    It handles user login or registration through a POST request.

    Attributes:
        permission_classes (tuple): Permissions required to access this view (AllowAny for public access).
        serializer_class (UserLoginOrRegistrationSerializer): The serializer used for input/output data.
        http_method_names (list): The allowed HTTP methods, in this case, only POST is allowed.

    Methods:
        post(request): Handles user login or registration logic.
    postc              
   O   s`  t j|jd}|jdd |jd}|jd}|jd}|r@|r@z
tjj||d}W n ty?   tjj|||d}Y nw |r^z	tjj|d	}W n ty]   tjj	|||d
}Y nw t
jj|d}	z|rstd|	jtj|gd |r~|r~t||	jd W n ty }
 ztdt|
itjdW  Y d}
~
S d}
~
ww t |}ddi|j}t|tjdS )z
        Handles user login or registration logic.

        Args:
            request (HttpRequest): The HTTP request containing user data.

        Returns:
            Response: The serialized user data or error response.
        dataTraise_exceptionmobile_numbermobile_country_codeemailr   r   )r   r   r   r   )r   r   r   userzYour EVChargy Login OTPsubjectotp_code
from_emailrecipient_listr   otpcustom_errorr   NmessagezOTP sent successfully)r   !UserLoginOrRegistrationSerializerr   is_validgetr   objectsr   createcreate_userr   create_or_update_coder   coder   
FROM_EMAILr   	Exceptionr	   strr   HTTP_400_BAD_REQUESTHTTP_200_OK)selfrequestargskwargs
serializerr   r   r   r!   	user_codeeresponse r@   [/var/www/html/evchargy.com/django-station-ev/station_ev/apps/account/views/account_views.pyr   '   s`   


"
zLoginOrRegistrationView.postN__name__
__module____qualname____doc__r   permission_classesr   r+   serializer_classhttp_method_namesr   r@   r@   r@   rA   r      s    r   c                   @   s*   e Zd ZdZefZdgZejZ	dd Z
dS ) VerifyLoginOrRegistrationOtpViewae  
    This view handles OTP verification for user login or registration.

    Attributes:
        permission_classes (tuple): Permissions required to access this view (AllowAny for public access).
        http_method_names (list): The allowed HTTP methods (only POST is allowed).

    Methods:
        post(request): Handles user OTP verification logic.
    r   c                 O   s\  t j|jd}|jdd |jd}|jd}|jd}|jd}|rF|rFz
tjj||d}	W n tyE   td	d
it	j
d Y S w |rdz	tjj|d}	W n tyc   td	dit	j
d Y S w ztjj|	|d}
|
 r{td	dit	j
dW S W n ty   td	dit	j
d Y S w t|	}|	j|	jdu |	j|	j|	jt|jt|d}t|S )a   
        Handles OTP verification logic for user login or registration.

        Args:
            request (HttpRequest): The HTTP request containing user data.

        Returns:
            Response: The serialized user data or an error response.
        r   Tr   r   r   r   r(   r   r*   zMUser Not Found: The mobile number you provided does not exist in our records.r   r   zEUser Not Found: The email you provided does not exist in our records.)r!   r2   z&OTP has been expired please try again!z*Invalid OTP! Please enter the correct OTP.N)idZis_new_userr   r   r   tokenrefresh)r   VerifyOtpSerializerr   r,   r-   r   r.   r   r	   r   r6   r   
is_expiredr   for_userrK   namer   r   r   r5   access_token)r8   r9   r:   r;   r<   r   r   r   r(   r!   r=   rM   response_datar@   r@   rA   r   y   sh   


	
	

	z%VerifyLoginOrRegistrationOtpView.postN)rC   rD   rE   rF   r   rG   rI   r   rN   rH   r   r@   r@   r@   rA   rJ   i   s    rJ   c                   @   r   )ResendOtpViewa  
    This view handles user login or registration and OTP resending for authentication.

    Attributes:
        permission_classes (tuple): Permissions required to access this view (AllowAny for public access).
        serializer_class (UserLoginOrRegistrationSerializer): The serializer used for input/output data.
        http_method_names (list): The allowed HTTP methods, in this case, only POST is allowed.

    Methods:
        post(request): Handles user login or registration and OTP resending logic.

    This view provides functionality for user login or registration,
    as well as resending OTP codes for authentication purposes.
    r   c              
   O   sZ  t j|jd}|jdd |jd}|jd}|jd}|r@|r@z
tjj||d}W n ty?   tdd	it	j
d
 Y S w |r^z	tjj|d}W n ty]   tddit	j
d
 Y S w tjj|d}	z|rstd|	jtj|gd |r~|r~t||	jd W n ty }
 ztdt|
it	j
d
W  Y d}
~
S d}
~
ww t |}|j}d|d< t|S )a  
        Handles user login or registration and OTP resending logic.

        Args:
            request (HttpRequest): The HTTP request containing user data.

        Returns:
            Response: The serialized user data or error response.

        This method processes user login or registration and resending OTP logic based on the provided mobile number
        and mobile country code.
        r   Tr   r   r   r   r   r*   z(The mobile number you entered is invalidr   r   z The email you entered is invalidr    z&Resend mail for Login/Registration OTPr"   r'   r)   Nz+OTP Sent Successfully to your email address)r   r+   r   r,   r-   r   r.   r   r	   r   r6   r   r1   r   r2   r   r3   r   r4   r5   )r8   r9   r:   r;   r<   r   r   r   r!   r=   r>   rS   r@   r@   rA   r      sd   


"
zResendOtpView.postNrB   r@   r@   r@   rA   rT      s    rT   c                   @   sL   e Zd ZdZejZej	 Z
eZddgZg dZdd Zdd Zd	d
 ZdS )ProfileModelViewSeta  
    This view handles OTP verification for user login or registration and user profile retrieval.

    Attributes:
        permission_classes (tuple): Permissions required to access this view (IsAuthenticated for authenticated users).
        http_method_names (list): The allowed HTTP methods (PUT and GET are allowed).

    Methods:
        list(request): Retrieves a list of user profiles (Not allowed, returns an error response).
        retrieve(request): Retrieves a specific user's profile details, with permission checks.
    rQ   r   )patchr-   deletec                 O   sn   |j jr0| |  }| |}|dur!| j|dd}| |jS | j|dd}t|jt	j
dS tg t	j
dS )a  
        Retrieves a list of user data based on the request parameters.

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

        Returns:
            Response: A response containing a list of serialized user data.

        This method retrieves a list of users records based on the provided request parameters.
        The list of stations is paginated for efficient retrieval.
        NT)manyr   )r!   is_superuserfilter_querysetget_querysetpaginate_querysetget_serializerget_paginated_responser   r	   r   r7   )r8   r9   r:   r;   querysetpager<   r@   r@   rA   list2  s   
zProfileModelViewSet.listc                 O   sH   |   }||jkr|jjstdditjdS | j|d|id}t|jS )a  
        Retrieve a specific user's profile details, with permission checks.

        Args:
            request (HttpRequest): The HTTP request for retrieving a user's profile.

        Returns:
            Response: The user's profile details or an error response if permission is denied.

        This method retrieves the profile details of a specific user, with permission checks to ensure
        that the requesting user has access to the requested profile.
        errorz9You do not have permission to access this user's profile.r   r9   )context)
get_objectr!   rY   r	   r   HTTP_403_FORBIDDENrH   r   )r8   r9   r:   r;   instancer<   r@   r@   rA   retrieveN  s   
zProfileModelViewSet.retrievec                 O   sH   |   }||jkr|jjstdditjdS | | tdditjdS )a  
        Handles the removal of account.

        Args:
            request (HttpRequest): The HTTP request object containing information about the account to delete.
            *args: Variable-length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            Response: A response indicating the success or failure of the account deletion operation.
        r*   z#You can't delete other user accountr   zAccount deleted successfully)rd   r!   rY   r	   r   r6   perform_destroyHTTP_204_NO_CONTENT)r8   r9   r:   r;   rf   r@   r@   rA   destroyg  s   
zProfileModelViewSet.destroyN)rC   rD   rE   rF   r   ZProfileSerializerrH   r   r.   allr_   r   filterset_classsearch_fieldsrI   ra   rg   rj   r@   r@   r@   rA   rU     s    
rU   c                   @   s   e Zd ZdZefZdd ZdS )UserLogoutViewa  
    This is the UserLogoutView class responsible for handling user logout through a POST request.

    It allows users to log out and blacklist the provided refresh token, ensuring the token can no longer be used.

    Attributes:
        permission_classes (tuple): Permissions required to access this view (IsAuthenticated for authenticated users).

    Methods:
        post(request): Handles user logout and token blacklisting logic.
    c              
   C   s   z|j d}|rt|}|  ttjdW S  ty)   tdditjd Y S  t	yR } zddl
}t|  tdt| d	tjdW  Y d}~S d}~ww )
a'  
        Handles user logout and token blacklisting logic.

        Args:
            request (HttpRequest): The HTTP request containing user data, including the refresh token.

        Returns:
            Response: A response indicating the success or failure of the logout operation.
        rM   r   r*   zInvalid token)r   r   r   Nz&There was some issue while logging out)r*   	traceback)r   r-   r   	blacklistr	   r   r7   r   r6   r4   ro   print
format_excr5   )r8   r9   Zrefresh_tokenrL   r>   ro   r@   r@   rA   r     s.   


zUserLogoutView.postN)rC   rD   rE   rF   r   rG   r   r@   r@   r@   rA   rn     s    rn   N)%django.confr   django.core.exceptionsr   rest_frameworkr   Zrest_framework.genericsr   Zrest_framework.permissionsr   r   rest_framework.responser	   rest_framework.viewsr
   Z#rest_framework_simplejwt.exceptionsr   Zrest_framework_simplejwt.tokensr   Z$apps.account.filters.profile_filtersr   Zapps.account.modelsr   r   Zapps.account.serializersr   Z
base.viewsr   Zaccount.utils.send_emailr   Zaccount.utils.send_otpr   r   rJ   rT   rU   rn   r@   r@   r@   rA   <module>   s(    UZ\c