
    
FZj!                     Z    d dl Z d dlZd dlZddlmZmZmZmZ ddlm	Z	m
Z
  G d de	      Zy)    N   )DaasGetQueryResultDaasGetJobStatusResult
DaasResultNOT_FULL_API_CALL_EXCEPTION   )APIDEFAULT_TIMEOUTc                        e Zd Zddddeddf fd	ZdedededefdZd	edefd
Z	dededefdZ
dedefdZdedefdZdedefdZdedefdZdedefdZdedefdZ xZS )AltitudeAPINzmy.geotab.comc	           
          t         
|   ||||||||       t        j                  t        j
                  t        j                  dd      }	y)a  
        A wrapper around mygeotab API for altitude users.

        :param username: The username used for MyGeotab servers. Usually an email address.
        :type username: str
        :param password: The password associated with the username. Optional if `session_id` is provided.
        :type password: str
        :param database: The database or company name. Optional as this usually gets resolved upon authentication.
        :type database: str
        :param session_id: A session ID, assigned by the server.
        :type session_id: str
        :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication.
        :type server: str or None
        :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes).
        :type timeout: float or None
        :param proxies: The proxies dictionary to apply to the request.
        :type proxies: dict or None
        :param cert: The path to client certificate. A single path to .pem file or a Tuple (.cer file, .key file).
        :type cert: str or Tuple or None
        :raise Exception: Raises an Exception if a username, or one of the session_id or password is not provided.
        )usernamepassworddatabase
session_idservertimeoutproxiescertz3%(asctime)s.%(msecs)03d %(levelname)-8s %(message)sz%Y-%m-%d %H:%M:%S)streamlevelformatdatefmtN)super__init__loggingbasicConfigsysstdoutINFO)selfr   r   r   r   r   r   r   r   _	__class__s             [C:\Users\Rodrigo\frota-trucks-cliente\python\Lib\site-packages\mygeotab/altitude/wrapper.pyr   zAltitudeAPI.__init__	   sV    B 	! 	 		
 ::,,H'	
    service_namefunction_namefunction_parametersreturnc                 0    | j                  d|||      }|S )NGetAltitudeData)methodserviceNamefunctionNamefunctionParameters)call)r!   r&   r'   r(   resultss        r$   	_call_apizAltitudeAPI._call_api;   s(    ))$$&2	  
 r%   respc                 n    |j                  dg       xs" |j                  di       j                  dg       S )z+Extracts errors from myG and daas wrappers.errors	apiResult)get)r!   r3   s     r$   _extract_errorszAltitudeAPI._extract_errorsD   s1    xx"%T+r)B)F)FxQS)TTr%   paramsc                 D   |dv sJ d}t        |      D ]+  }	 | j                  |d   ||d         }t        |       |c S  y
# t        $ rS}|t        k(  r>||dz
  k(  r|t        dt               d       t        j                  |dz   d	z         n|Y d
}~d
}~ww xY w)zy
        Supports getJobStatus calls, and getQueryResults calls. Retries in case of errors like connection rest.
        )getJobStatusgetQueryResultscreateQueryJob   r-   r/   )r&   r'   r(   r   z2encountered error trying to parse to api response z, retrying....
   N)	ranger2   r   	Exceptionr   printstrtimesleep)r!   r'   r9   	max_tries	try_indexcall_resultes          r$   call_apizAltitudeAPI.call_apiI   s      UUUU	y)I"nn!'!6"/(./C(D - 
 ;'"" *  33 IM1 RSVWbScRddrst

IMR#78G 9s   &A	BA	BBc                     	 | j                  d|      }| j                  |      }|rt        |d   j                  dd            |d   d   d   S # t        $ r}t	        j
                  d	|        |d
}~ww xY w)z8
        creates the job with the given params.
        r=   )r'   r9   )r3   r   messagezFailed to create the jobr6   r1   Exception: N)rJ   r8   rA   r7   r   error)r!   r9   r1   r5   rI   s        r$   
create_jobzAltitudeAPI.create_jobb   s    	mm. $ G
 ))w)7Fq	i9S TUU;'	2155 	MMKs+,G	s   AA 	A:A55A:c                 @    | j                  d|      }t        |      }|S )zY
        checks the status of a given job. jobId needs to be included in params.
        r;   )rJ   r   )r!   r9   rH   daas_statuss       r$   check_job_statuszAltitudeAPI.check_job_statusu   s$     mmNF;,[9r%   c                    	 	 | j                  |      }|j                  r't        |j                        dkD  r|j                  d   |j                         r	 |j                  S t	        j
                  d       t        j                  d|j                          # t        $ rA}t        j                  d|        t        j                  dj                          |d}~ww xY w)zn
        waits for a job to finish running and returns the job. jobId needs to be included in params.
        r   r>   zwaiting for results: rM   z8error: error while waiting for job to complete, result: N)rR   r5   lenhas_finishedrD   rE   r   infojobrA   rN   )r!   r9   rQ   rI   s       r$   wait_for_job_to_completez$AltitudeAPI.wait_for_job_to_complete}   s     "33F;%%#k.@.@*AA*E%,,Q//"//1  

14[__4EFG   A3/0 XYdYhYhXijks   AB $7B 	C&%<C!!C&c              #   n  K   d}| j                  |      }|j                  rt        |j                        dkD  s|j                         st	        d      |r	 | j                  d|      }t        |      }|j                  }|j                  }|j                  }|j                  }	|dk(  rt        j                  d|	        ||d   d<   ||	|g|j                  d |dz  }|sd	}d	 |ry	y	# t        $ r9}
t        j                  d
|
        t        j                  d        d	}|
d	}
~
ww xY ww)zX
        fetch data for the given params. jobId needs to be included in params.
        r   r   z8fetch data was called before job had finished correctly.r<   ztotal number of rows: r/   	pageToken)datar5   NrM   z+error: error while fetching data, results: )rR   r5   rT   rU   rA   rJ   r   rW   rows
page_token
total_rowsr   rV   rN   )r!   r9   indexrQ   rH   daas_resultr1   r\   r]   r^   rI   s              r$   
fetch_datazAltitudeAPI.fetch_data   s:     ++F3#k&8&8"9A"=kF^F^F`VWW"mm,=vF0=%//"''(33
(33
A:LL#9*!FG<F+,[9 $j%8KDVDVWW
! E# $  A3/0 KG9UV	s1   AD5BC0 +D5.D50	D294D--D22D5c                    g }| j                  |      }|D ]  }	 t        |      t        k(  rt        d|      |g n|d   d   }|dk(  rdn|j	                  dd      }|r.t        |      dkD  r t        j                  d|d           |d   |j                  |        |S # t        $ r}t        j                  d|        |d}~ww xY w)z
        uses and iterates through fetch_data for the given params, and returns the combined data. jobId needs to be included in params.
        zrecieved error:Nr[   r   r5   zgot error when getting data: z$error: error while combining data:: )	ra   typerC   rA   r7   rT   r   rN   extend)r!   r9   r[   results_iterator	data_pagepager5   rI   s           r$   get_datazAltitudeAPI.get_data   s     ??62)I	?c)#$5yAA&.rIf4Ea4H'0D'8timmHVZ>[c&kAoMM$A&)"MN )OD! *    DQCHIs   BB""	C
+CC
c                    t        j                  d       | j                  |      }t        j                  d|        |d   |d   d<   t        j                  d       | j                  |      }t        j                  d|        t        j                  d       | j	                  |      }t        j                  d	       |S )
zq
        given the parameters, will call the request, wait on it to finish and return the combined data.
        zcreating jobzjob created: idr/   jobIdzchecking the job statuszjob finished: zgathering resultzdata gathered)r   rV   rO   rX   rh   )r!   r9   rW   r1   r[   s        r$   dozAltitudeAPI.do   s     	|%oof%}SE*+03D	#$W-.0//7~gY/0')}}V$}&r%   )__name__
__module____qualname__r
   r   rC   dictr2   listr8   rJ   rO   r   rR   rX   ra   rh   rl   __classcell__)r#   s   @r$   r   r      s     0
dc # TX ]a UD UT U
c 4 D 2 $ &t 0F t  , $ Bt  * $ r%   r   )r   rD   r   daas_definitionr   r   r   r   apir	   r
   r    r%   r$   <module>rv      s%    
   p p &O# Or%   