
    si9                        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 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 d dlmZmZ d dlmZ d dlm Z   G d dejB                        Z" G d dee      Z# G d de      Z$ ejJ                  d      rd dlm&Z&  G d dejB                  e      Z' ejJ                  d      rd dl(m)Z)  G d dejB                  e      Z*yy)     )	timedeltatimezone)chain)apps)models)Q)ValidationError)reverse_lazy)r   )Credentials)HorillaCompanyManager)Company)Employee)_thread_locals)HorillaModelNoPermissionModelrender_template)	Candidatec                   F   e Zd ZdZ ej
                  ddd      Z ej
                  d      Z ej
                  d      Z ej                  d      Z
 ej                  eej                  ddd	      Z ed
      Zed        Zd Zd Zd Zd Zd Zd Z G d d      Zy)GoogleCloudCredentialz
    Model representing Google Cloud credentials associated with a specific company.
    Stores the client ID, client secret, redirect URIs, and the project ID for each set of credentials.
       T)
max_lengthblanknullr   zComma separated URIs)	help_textr   )	on_deleter   r   verbose_name
company_idc                 |    | j                   j                  d      D cg c]  }|j                          }}|S c c}w )a  
        Property that returns a list of redirect URIs by splitting the
        comma-separated string in the `redirect_uris` field and stripping
        any surrounding whitespace from each URI.

        Returns:
            list: A list of redirect URIs (strings).
        ,)redirect_urissplitstrip)selfuriurl_lists      7/var/www/python-projects/worksol/horilla_meet/models.pyredirect_uri_listz'GoogleCloudCredential.redirect_uri_list)   s9     ,0+=+=+C+CC+HICCIIKII Js   9c                 4    t        dd| j                  i      S )z
        Returns the URL for updating the Google Cloud credentials instance.

        Returns:
            str: The URL for updating the credentials instance.
        zupdate-gmeet-credentialspkkwargsr
   r+   r%   s    r(   get_update_urlz$GoogleCloudCredential.get_update_url6   s     6dggOO    c                 4    t        dd| j                  i      S )z
        Returns the URL for deleting the Google Cloud credentials instance.

        Returns:
            str: The URL for deleting the credentials instance.
        zdelete-gmeet-credentialsobj_idr,   r.   r/   s    r(   get_delete_urlz$GoogleCloudCredential.get_delete_url?   s     6$''?RSSr1   c                     | j                   S )z
        Returns the unique identifier (primary key) of the GoogleCloudCredential instance.

        Returns:
            int: The primary key (ID) of the credential instance.
        )r+   r/   s    r(   get_instance_idz%GoogleCloudCredential.get_instance_idH   s     wwr1   c                 &    d| j                    d}|S )z
        Returns an HTML snippet that hides the actual client ID value and displays
        a placeholder (masked version) for the client ID in a UI table column.

        Returns:
            str: An HTML string to represent a masked client ID.
        1
        <span class="oh-hidden-item" data-value=%>********************</span>
        )	client_idr%   cols     r(   get_client_id_colz'GoogleCloudCredential.get_client_id_colQ   s%    1150@ A	 
r1   c                 &    d| j                    d}|S )a
  
        Returns an HTML snippet that hides the actual client secret value and displays
        a placeholder (masked version) for the client secret in a UI table column.

        Returns:
            str: An HTML string to represent a masked client secret.
        r8   r9   )client_secretr;   s     r(   get_client_secret_colz+GoogleCloudCredential.get_client_secret_col^   s'    1151C1C0D E	 
r1   c                 N    | j                   }dj                  d |D              }|S )z
        Returns an HTML snippet that returns the redirect urls as the points

        Returns:
            str: An HTML string to represent the redirect url list.
        z<br /> <br />c              3   "   K   | ]  }|  	 y w)N ).0urls     r(   	<genexpr>z9GoogleCloudCredential.get_redirect_url.<locals>.<genexpr>t   s     "@cU8"@s   )r)   join)r%   r'   r<   s      r(   get_redirect_urlz&GoogleCloudCredential.get_redirect_urlk   s*     ))"""@x"@@
r1   c                        e Zd ZdZdZdZddgZy)GoogleCloudCredential.Metaz
        Metadata for the GoogleCloudCredential model.
        Defines the verbose name for display and sets a unique constraint
        on the combination of `project_id` and `company_id`.
        zGoogle Cloud CredentialzGoogle Cloud Credentials
project_idr   N)__name__
__module____qualname____doc__r   verbose_name_pluralunique_togetherrC   r1   r(   MetarJ   x   s    	 18'6r1   rR   N)rL   rM   rN   rO   r   	CharFieldrK   r:   r?   	TextFieldr"   
ForeignKeyr   PROTECTr   r   objectspropertyr)   r0   r4   r6   r=   r@   rH   rR   rC   r1   r(   r   r      s    
 "!!S4HJ   C0I$F$$4M$F$$/EFM"""..J $L1G
 
PT	7 	7r1   r   c                   d   e Zd ZdZ ej
                  eej                  d      Z ej                         Z
 ej                         Z ej                  d      Z ej                  d      Z ej                  d      Z ej                         Z ej"                         Zd Zed        Zd Zy	)
GoogleCredentialz
    Model representing Google credentials for an employee, including
    token information, client ID, client secret, scopes, and expiration time.
    google_credentialr   related_namer   r   c           
          t        | j                  | j                  | j                  | j                  | j
                  | j                  j                  d      | j                        S )aR  
        Converts the GoogleCredential model instance into a Google `Credentials` object.

        This method is useful for using the stored credentials to authenticate
        requests to Google APIs.

        Returns:
            Credentials: A `Credentials` object populated with the data
            from the model instance.
        r!   )tokenrefresh_token	token_urir:   r?   scopesexpiry)	r   r_   r`   ra   r:   r?   rb   r#   
expires_atr/   s    r(   to_google_credentialsz&GoogleCredential.to_google_credentials   sQ     **,,nnnn,,;;$$S)??
 	
r1   c                     | j                   j                  ||j                  |j                  |j                  |j
                  |j                  dj                  |j                        |j                  d       y)a>  
        Creates or updates a GoogleCredential instance from a Google `Credentials` object.

        This method is typically used to persist or refresh the credentials
        of an employee by extracting the relevant information from a `Credentials`
        object and storing it in the database.

        Args:
            employee (Employee): The employee to associate with the credentials.
            credentials (Credentials): A Google `Credentials` object containing the
            token, refresh_token, client_id, client_secret, and other related fields.

        r!   )r_   r`   ra   r:   r?   rb   rd   )employee_iddefaultsN)
rW   update_or_creater_   r`   ra   r:   r?   rG   rb   rc   )clsemployeecredentialss      r(   from_google_credentialsz(GoogleCredential.from_google_credentials   sk     	$$ $**!,!:!:(22(22!,!:!:((;#5#56)00 	% 	
r1   c                      d| j                    S )a-  
        Returns a string representation of the GoogleCredential instance,
        typically used for displaying the object in the admin interface or logs.

        Returns:
            str: A string that represents the GoogleCredential instance with
            the associated employee's ID.
        zGoogle credential - )rg   r/   s    r(   __str__zGoogleCredential.__str__   s     &d&6&6%788r1   N)rL   rM   rN   rO   r   OneToOneFieldr   CASCADErg   rT   r_   r`   rS   ra   r:   r?   rb   DateTimeFieldrd   re   classmethodrm   ro   rC   r1   r(   rZ   rZ      s    
 '&&&FNN9LK FE$F$$&M   C0I   C0I$F$$4MVF%%%'J
* 
 
6	9r1   rZ   c                       e Zd ZdZ ej
                  eej                  d      Z ej                  d      Z
 ej                         Z ej                         Z ej                         Z ej                  dd      Z ej$                  d	d
      Z ej(                  edd      Z G d d      Zd Zed        Zd Zd Zd Zd Zd Zd Z d Z! fdZ" xZ#S )GoogleMeetingad  
    Model representing a Google meeting scheduled by an employee.
    Stores information about the meeting's title, description, start time,
    duration, attendees, and related event data.

    The model also includes methods for generating URLs for update/delete operations
    and handling attendees, as well as calculating the meeting's end time.
    meetingsr\      r   r   T)r   r   <   zDuration in minutes)defaultr   )ry   r   r   c                   h    e Zd ZdZdgZ ej                  ddg       ej                  dg      gZy)GoogleMeeting.Metaz
        Metadata for GoogleMeeting model.
        Orders meetings by start time in descending order and creates indexes
        on `employee_id` and `start_time`, as well as `event_id` for optimized queries.
        z-start_timerg   
start_time)fieldsevent_idN)rL   rM   rN   rO   orderingr   IndexindexesrC   r1   r(   rR   r{      s:    	 "?FLL =>FLL-
r1   rR   c                 V    | j                    d| j                  j                  d       S )a:  
        Returns a string representation of the GoogleMeeting instance, typically used
        for displaying the meeting's title and formatted start time in the admin interface or logs.

        Returns:
            str: A string combining the meeting's title and start time in 'YYYY-MM-DD HH:MM' format.
        z - z%Y-%m-%d %H:%M)titler|   strftimer/   s    r(   ro   zGoogleMeeting.__str__   s*     **S!9!9:J!K LMMr1   c                 H    | j                   t        | j                        z   S )a  
        Calculates the end time of the meeting based on its start time and duration.

        The end time is computed by adding the meeting's duration (in minutes) to the start time.

        Returns:
            datetime: The calculated end time of the meeting.
        )minutes)r|   r   durationr/   s    r(   end_timezGoogleMeeting.end_time   s     4==!AAAr1   c                     t        j                  | j                        }d|j                          d|j	                          d}|S )a  
        Provides a custom HTML representation of the meeting's start time,
        splitting the date and time into separate spans for easier styling or manipulation.

        Returns:
            str: HTML string containing the start date and time in separate spans.
        z>
            <span class="oh-hidden-item dateformat_changer" >zF</span>,
            <span class="oh-hidden-item timeformat_changer" >z</span>
        )r   	localtimer|   datetime)r%   r|   r<   s      r(   start_time_strzGoogleMeeting.start_time_str
  sQ     ''8
>>Hoo>O=P Q>>Hoo>O=P Q	 
r1   c                 &    d| j                    d}|S )a  
        Generates a custom HTML representation of the meeting's title column.
        This includes a button for collapsing/expanding the section and displays the title of the meeting.
        The method separates the date and time into different spans to allow easier styling or manipulation if required.

        The HTML output includes:
        - A button to toggle between collapsed and expanded states (using `ion-icon` for the up/down chevron).
        - The title of the meeting, displayed inside a span with the class `oh-permission-table__user`.

        Returns:
            str: An HTML string representing the meeting's title column with collapse functionality.
        ad  
            <div class="oh-permission-table--toggle" onclick="event.stopPropagation()"
                >
                <div class="d-flex align-items-center">
                    <button class="oh-permission-table__collapse me-2">
                        <span title="Reveal"><ion-icon class="oh-permission-table__collapse-down" name="chevron-down-outline"></ion-icon></span>
                        <span title="Collapse"><ion-icon class="oh-permission-table__collapse-up" name="chevron-up-outline"></ion-icon></span>
                    </button>
                    <span class="oh-permission-table__user">z:</span>
                </div>
            </div>
        )r   r;   s     r(   get_title_columnzGoogleMeeting.get_title_column  s'    = >BZZL I	 
r1   c                    t         j                  j                  t        | j                        t        | j                        z        }t
        j                  j                  | j                        }t        t        ||            S )N)employee_work_info__email__in)	email__in)r   rW   filterr   	attendeesr   listr   )r%   	employees
candidatess      r(   get_attendeeszGoogleMeeting.get_attendees6  sf    $$++DNN;$..)*
	 &&---G
E)Z011r1   c                      t        dd| i      S )a  
        Returns a custom HTML representation of the meeting's attendees column by rendering a template.

        This is used to display attendees in a specific format or style on a web page.

        Returns:
            str: Rendered HTML for displaying the attendees.
        z"gmeet/attendees_custom_column.htmlinstance)pathcontextr   r/   s    r(   get_attendees_columnz"GoogleMeeting.get_attendees_column@  s     5&
 	
r1   c                 4    t        dd| j                  i      S )z
        Returns the URL for updating the GoogleMeeting instance.

        The URL is dynamically generated to include the primary key of the meeting instance.

        Returns:
            str: The URL to update the meeting.
        zupdate-gmeetr+   r,   r.   r/   s    r(   r0   zGoogleMeeting.get_update_urlO  s     ND$''?CCr1   c                 8    t        dd| j                  i      }|S )z
        Returns the URL for deleting the GoogleMeeting instance.

        The URL is a generic delete view, allowing for the deletion of the meeting instance.

        Returns:
            str: The URL to delete the meeting.
        zdelete-google-meetidr,   r.   )r%   rE   s     r(   r4   zGoogleMeeting.get_delete_urlZ  s     /twwH
r1   c                 4    t        dd| j                  i      S )Nzgmeet-detail-viewr+   r,   r.   r/   s    r(   detailed_urlzGoogleMeeting.detailed_urlf  s    /twwHHr1   c                 0   t        t        d      }|j                  j                  | _        | j
                  sO| j                  rCt        j                  j                  | j                        j                         rt        d      t        | 4  |i | y)a!  
        Saves the GoogleMeeting instance to the database.

        Before saving, checks if the `event_id` already exists in the database for another meeting.
        If so, raises a validation error to prevent duplicate meetings with the same event.

        Args:
            *args: Additional positional arguments passed to the parent save method.
            **kwargs: Additional keyword arguments passed to the parent save method.

        Raises:
            ValidationError: If a meeting with the same `event_id` already exists.
        request)r~   z&Meeting with this Event already existsN)getattrr   useremployee_getrg   r+   r~   ru   rW   r   existsr	   supersave)r%   argsr-   r   	__class__s       r(   r   zGoogleMeeting.savei  st     .)4"<<44 %%,,dmm,DKKM!"JKKd%f%r1   )$rL   rM   rN   rO   r   rU   r   rq   rg   rS   r   rT   descriptionrr   r|   URLFieldmeet_urlr~   PositiveIntegerFieldr   	JSONFieldr   r   rR   ro   rX   r   r   r   r   r   r0   r4   r   r   __classcell__)r   s   @r(   ru   ru      s     $&##FNNK F,E"&""$K%%%'Jv Hv3T:H*v**2AVWH   TEI
 
N 	B 	B 82
	D
I& &r1   ru   recruitment)InterviewSchedulec                       e Zd Z ej                  eej                  d      Z ej                  eej                        Z	y)InterviewMeetingLinkgoogle_interviewsr\   r   N)
rL   rM   rN   r   rp   r   rq   	interviewru   meetingrC   r1   r(   r   r     s;    (F((nn,
	
 '&&&}Or1   r   pms)Meetingsc                       e Zd Z ej                  eej                  d      Z ej                  eej                        Z	y)PmsMeetingLinkgoogle_meetingr\   r   N)
rL   rM   rN   r   rp   r   rq   r   ru   r   rC   r1   r(   r   r     s:    &&&&=M
 .--mv~~Vr1   r   N)+datetimer   r   	itertoolsr   django.appsr   	django.dbr   django.db.modelsr   django.formsr	   django.urlsr
   django.utilsgoogle.oauth2.credentialsr   base.horilla_company_managerr   base.modelsr   employee.modelsr   horilla.horilla_middlewaresr   horilla.modelsr   r   horilla_views.cbv_methodsr   recruitment.modelsr   Modelr   rZ   ru   is_installedr   r   
pms.modelsr   r   rC   r1   r(   <module>r      s    (     ( $ ! 1 >  $ 6 : 5 (k7FLL k7\K9|%6 K9\n&L n&b 4]#4Pv||-> P 4U#W'8 W r1   