o
    tBh4                     @   sh   d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dl	Z	d dl
Zd dlmZ G dd deZdS )    N)mktime)quotec                   @   s   e Zd ZdZedd Zedd Zed#dd	Zed$ddZedd Z	e	
d$ddZ
edd Ze	
d$ddZe	
d$ddZedd Zedd 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 )%	APIHelpera/  A Helper Class for various functions associated with API Calls.

    This class contains static methods for operations that need to be
    performed during API requests. All of the methods inside this class are
    static methods, there is no need to ever initialise an instance of this
    class.

    c                 C   s   |   }|| |S )a  Merges two dictionaries into one as a shallow copy.

        Args:
            dict1 (dict): The first dictionary.
            dict2 (dict): The second dictionary.

        Returns:
            dict: A dictionary containing key value pairs
            from both the argument dictionaries. In the case
            of a key conflict, values from dict2 are used
            and those from dict1 are lost.

        )copyupdate)dict1dict2temp r
   h/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/square/api_helper.pymerge_dicts   s   
zAPIHelper.merge_dictsc                 C   sr   | du rdS t | tr)t }| D ]}t|dr |t| q|| q|} n
t| dr3t| } t| dS )zJSON Serialization of a given object.

        Args:
            obj (object): The object to serialize.

        Returns:
            str: The JSON serialized string of the object.

        N_namesF)
isinstancelisthasattrappendr   to_dictionary
jsonpickleencode)objvalueitemr
   r
   r   json_serialize-   s   



zAPIHelper.json_serializeNFc                    s|   | du rdS zt | }W n ty   |  Y S w  du r|S |r, fdd| D S t|tr: fdd|D S  |S )a  JSON Deserialization of a given string.

        Args:
            json (str): The JSON serialized string to deserialize.

        Returns:
            dict: A dictionary representing the data contained in the
                JSON serialized string.

        Nc                    s   i | ]	\}}| |qS r
   r
   .0kvunboxing_functionr
   r   
<dictcomp>b       z.APIHelper.json_deserialize.<locals>.<dictcomp>c                    s   g | ]} |qS r
   r
   r   elementr   r
   r   
<listcomp>d       z.APIHelper.json_deserialize.<locals>.<listcomp>)r   decode
ValueErroritemsr   r   )jsonr   as_dictdecodedr
   r   r   json_deserializeJ   s   
zAPIHelper.json_deserializeindexedc                    s   g }t jd dk rttttttjt	j
f}n
tttttjt	j
f}t|d |r_|dkr7| fdd|D 7 }|S |dkrJ| fddt|D 7 }|S |dkr[| fd	d|D 7 }|S td
| fddt|D 7 }|S )aW  Converts an array parameter to a list of key value tuples.

        Args:
            key (str): The name of the parameter.
            array (list): The value of the parameter.
            formatting (str): The type of key formatting expected.

        Returns:
            list: A list with key value tuples for the array elements.

        r      	unindexedc                    s   g | ]	}d   |fqS )z{0}[]formatr!   keyr
   r   r#   ~   r    z-APIHelper.serialize_array.<locals>.<listcomp>r,   c                        g | ]\}}d   ||fqS z{0}[{1}]r/   r   indexr"   r1   r
   r   r#           plainc                    s   g | ]} |fqS r
   r
   r!   r1   r
   r   r#      r$   zInvalid format provided.c                    r3   r4   r/   r5   r1   r
   r   r#      r7   )sysversion_infostrintlongfloatbooldatetimedater   
CustomDater   	enumerater&   )r2   array
formattingtuplesserializable_typesr
   r1   r   serialize_arrayh   s"   
zAPIHelper.serialize_arrayc                    s   | du rt d|du r| S |D ]B}|| d }|| d  d}|du r'd}n t|tr9d fdd|D }n rCtt|dd	nt|}| d
|t|} q| S )a  Replaces template parameters in the given url.

        Args:
            url (str): The query url string to replace the template parameters.
            parameters (dict): The parameters to replace in the url.

        Returns:
            str: URL with replaced parameters.

        NURL is None.r   r    /c                 3   s,    | ]} rt t|d dnt|V  qdS rJ   safeNr   r;   r   xr   r
   r   	<genexpr>   s   * z@APIHelper.append_url_with_template_parameters.<locals>.<genexpr>rM   z{{{0}}})r&   r   r   joinr   r;   replacer0   )url
parametersr2   r   replace_valuer
   rR   r   #append_url_with_template_parameters   s   
z-APIHelper.append_url_with_template_parametersc                 C   s0  | du rt d|du r| S | D ]\}}d| v rdnd}|durt|trdd |D }|dkrD| d||d	d
d |D 7 } q|dkrZ| d||ddd |D 7 } q|dkrp| d||ddd |D 7 } q| d|ddd t|||D 7 } q| d||tt	|dd7 } q| S )a>  Adds query parameters to a URL.

        Args:
            url (str): The URL string.
            parameters (dict): The query parameters to add to the URL.
            array_serialization (str): The format of array parameter serialization.

        Returns:
            str: URL with added query parameters.

        NrI   ?&c                 S   s   g | ]}|r|qS r
   r
   r!   r
   r
   r   r#      r$   z>APIHelper.append_url_with_query_parameters.<locals>.<listcomp>csvz
{0}{1}={2},c                 s        | ]}t t|d dV  qdS rL   rO   rP   r
   r
   r   rS          z=APIHelper.append_url_with_query_parameters.<locals>.<genexpr>psv|c                 s   r^   rL   rO   rP   r
   r
   r   rS      r_   tsv	c                 s   r^   rL   rO   rP   r
   r
   r   rS      r_   z{0}{1}c                 s   s,    | ]\}}d  |tt|ddV  qdS )z{0}={1}rJ   rM   N)r0   r   r;   r   r
   r
   r   rS      s     rJ   rM   )
r&   r'   r   r   r0   rT   r   rH   r   r;   )rV   rW   array_serializationr2   r   	seperatorr
   r
   r    append_url_with_query_parameters   sH   

z*APIHelper.append_url_with_query_parametersc                 C   s   d}t || }|du rtd|d}| d}| t||dkr$|nd }t dd|}|dkr9| |d nd	}|| | S )
zValidates and processes the given query Url to clean empty slashes.

        Args:
            url (str): The given query Url to process.

        Returns:
            str: Clean Url as string.

        z^https?://[^/]+NzInvalid Url format.r   rZ   z//+rK   rJ   )rematchr&   groupfindlensub)rV   regexri   protocolr6   	query_urlrW   r
   r
   r   	clean_url   s   

zAPIHelper.clean_urlc                 C   s,   g }|   D ]\}}|t|||7 }q|S )aj  Form encodes a dictionary of form parameters

        Args:
            form_parameters (dictionary): The given dictionary which has
            atleast one model to form encode.
            array_serialization (str): The format of array parameter serialization.

        Returns:
            dict: A dictionary of form encoded properties of the model.

        )r'   r   form_encode)form_parametersrd   encodedr2   r   r
   r
   r   form_encode_parameters   s   z APIHelper.form_encode_parametersc                 C   s   g }| du rg S t | tr&t|| |D ]}|t|d |d |7 }q|S t | trC| D ]}|t| | |d | d |7 }q-|S ||| f |S )a  Encodes a model in a form-encoded manner such as person[Name]

        Args:
            obj (object): The given Object to form encode.
            instance_name (string): The base name to appear before each entry
                for this object.
            array_serialization (string): The format of array parameter serialization.

        Returns:
            dict: A dictionary of form encoded properties of the model.

        N   r   [])r   r   r   rH   rr   dictr   )r   instance_namerd   retvalr"   r   r
   r
   r   rr     s   

$zAPIHelper.form_encodec                 C   s   t  }dd | j D D ]k}t| |}t|tr;t || j| < |D ]}|| j|  t|dr6t	
|n| q#qt|t rgt  || j| < |D ]}t|| drZt	
|| n|| || j|  |< qJqt|drqt	
|n||| j| < q|S )a  Creates a dictionary representation of a class instance. The
        keys are taken from the API description and may differ from language
        specific variable names of properties.

        Args:
            obj: The object to be converted into a dictionary.

        Returns:
            dictionary: A dictionary form of the model with properties in
            their API formats.

        c                 S   s   i | ]\}}|d ur||qS Nr
   r   r
   r
   r   r   C  s    z+APIHelper.to_dictionary.<locals>.<dictcomp>r   )ry   __dict__r'   getattrr   r   r   r   r   r   r   )r   
dictionarynamer   r   r2   r
   r
   r   r   2  s   

*
4$zAPIHelper.to_dictionaryc                 C   s   |r| |S d S r|   r
   )funcr   r
   r
   r   when_definedU  s   zAPIHelper.when_definedc                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )zAPIHelper.CustomDatez A base class for wrapper classes of datetime.

        This class contains methods which help in
        appropriate serialization of datetime objects.

        Nc                 C   s$   || _ |s| || _d S || _d S r|   )r@   from_datetimer   )selfdtimer   r
   r
   r   __init__b  s   
zAPIHelper.CustomDate.__init__c                 C   s
   t | jS r|   )r;   r   r   r
   r
   r   __repr__i  s   
zAPIHelper.CustomDate.__repr__c                 C   s   | j S r|   )r   r   r
   r
   r   __getstate__l  s   z!APIHelper.CustomDate.__getstate__c                 C   s   d S r|   r
   )r   stater
   r
   r   __setstate__o  s   z!APIHelper.CustomDate.__setstate__r|   )__name__
__module____qualname____doc__r   r   r   r   r
   r
   r
   r   rB   Y  s    
rB   c                   @   (   e Zd ZdZedd Zedd ZdS )zAPIHelper.HttpDateTimez: A wrapper class for datetime to support HTTP date format.c                 C   s   t jt| dddS )NFT)timeval	localtimeusegmt)eut
formatdater   	timetuplecls	date_timer
   r
   r   r   v  s   z$APIHelper.HttpDateTime.from_datetimec                 C   s"   t j tt|}| ||S r|   )r@   fromtimestampr   	mktime_tzparsedate_tzr   r   r   r
   r
   r   
from_value{  s   
z!APIHelper.HttpDateTime.from_valueNr   r   r   r   classmethodr   r   r
   r
   r
   r   HttpDateTimer  s    
r   c                   @   r   )zAPIHelper.UnixDateTimez: A wrapper class for datetime to support Unix date format.c                 C   s   t | S r|   )calendartimegmutctimetupler   r
   r
   r   r     s   z$APIHelper.UnixDateTime.from_datetimec                 C   s   t j t|}| |t|S r|   )r@   utcfromtimestampr>   r   r
   r
   r   r     s   z!APIHelper.UnixDateTime.from_valueNr   r
   r
   r
   r   UnixDateTime      
r   c                   @   r   )zAPIHelper.RFC3339DateTimez9 A wrapper class for datetime to support Rfc 3339 format.c                 C   s   |  S r|   )	isoformatr   r
   r
   r   r     s   z'APIHelper.RFC3339DateTime.from_datetimec                 C   s   t j|}| ||S r|   )dateutilparserparser   r
   r
   r   r     s   
z$APIHelper.RFC3339DateTime.from_valueNr   r
   r
   r
   r   RFC3339DateTime  r   r   )NF)r,   )r   r   r   r   staticmethodr   r   r+   rH   rY   rf   rq   ru   rr   r   r   objectrB   r   r   r   r
   r
   r
   r   r      s>    	

!
#6

"
r   )rh   r9   r@   r   email.utilsutilsr   timer   r   dateutil.parserr   requests.utilsr   r   r   r
   r
   r
   r   <module>   s   