o
    ;Di_                     @   s   d dl mZmZmZ d dlmZmZ d dlmZ d dl	m
Z dd Zddd	Zdd
dZ		dddZG dd deZ		dddZ		dddZee_ee_dS )    )absolute_importprint_functiondivision)Tableiterdata)	text_type)ArgumentErrorc                 C   sr   dd l }t| |jr| S t| tr|| }|S dd l}t| |jjjr+|	| }|S | d u r5| }|S t
d)Nr   z$gspread: Invalid account credentials)gspread
isinstanceClientdictservice_account_from_dictgoogleoauth2service_accountCredentials	authorizePetlArgError)	auth_infor	   gdr   gcga r   G/var/www/Datamplify/venv/lib/python3.10/site-packages/petl/io/gsheet.py_get_gspread_client	   s   


r   Fc                 C   s^   |r ddl m} z| |}W |S  |y   | |}Y |S w |d ur+| |}|S td)Nr   )SpreadsheetNotFoundz%gspread requires argument spreadsheet)gspread.exceptionsr   open_by_keyopenr   )gspread_clientspreadsheetr   r   wbr   r   r   _open_spreadsheet   s   
r"   c                 C   s   |d u r	| j }|S t|tr| |}|S t|trBt|}|r;|dd |  D v r2| |}|S | |dd}|S | |}|S td)Nc                 S   s   g | ]}|j qS r   title).0wbsr   r   r   
<listcomp>3   s    z%_select_worksheet.<locals>.<listcomp>   z,Only can find worksheet by name or by number)	sheet1r
   intget_worksheetr   
worksheets	worksheetadd_worksheetr   )r!   r-   find_or_createws	sheetnamer   r   r   _select_worksheet*   s"   




r2   Nc                 C   s   t | ||||S )a  
    Extract a table from a google spreadsheet.

    The `credentials_or_client` are used to authenticate with the google apis.
    For more info, check `authentication`_. 

    The `spreadsheet` can either be the key of the spreadsheet or its name.

    The `worksheet` argument can be omitted, in which case the first
    sheet in the workbook is used by default.

    The `cell_range` argument can be used to provide a range string
    specifying the top left and bottom right corners of a set of cells to
    extract. (i.e. 'A1:C7').

    Set `open_by_key` to `True` in order to treat `spreadsheet` as spreadsheet key.

    .. note::
        - Only the top level of google drive will be searched for the 
          spreadsheet filename due to API limitations.
        - The worksheet name is case sensitive.

    Example usage follows::

        >>> from petl import fromgsheet
        >>> import gspread # doctest: +SKIP
        >>> client = gspread.service_account() # doctest: +SKIP
        >>> tbl1 = fromgsheet(client, 'example_spreadsheet', 'Sheet1') # doctest: +SKIP
        >>> tbl2 = fromgsheet(client, '9zDNETemfau0uY8ZJF0YzXEPB_5GQ75JV', credentials) # doctest: +SKIP

    This functionality relies heavily on the work by @burnash and his great 
    `gspread module`_.

    .. _gspread module: http://gspread.readthedocs.io/
    .. _authentication: http://gspread.readthedocs.io/en/latest/oauth2.html
    )GoogleSheetView)credentials_or_clientr    r-   
cell_ranger   r   r   r   
fromgsheet?   s   )r6   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )r3   z2Conects to a worksheet and iterates over its rows.c                 C   s"   || _ || _|| _|| _|| _d S N)r   r    r-   r5   r   )selfr4   r    r-   r5   r   r   r   r   __init__t   s
   
zGoogleSheetView.__init__c                 C   sD   t | j}t|| j| j}t|| j}| jd ur| |S | 	|S r7   )
r   r   r"   r    r   r2   r-   r5   _yield_by_range_yield_all_rows)r8   r   r!   r0   r   r   r   __iter__~   s   



zGoogleSheetView.__iter__c                 c   s    |  D ]}t|V  qd S r7   )get_all_valuestuple)r8   r0   rowr   r   r   r;      s   zGoogleSheetView._yield_all_rowsc                 c   s&    | | j}|D ]}t|V  q	d S r7   )
get_valuesr5   r>   )r8   r0   foundr?   r   r   r   r:      s
   zGoogleSheetView._yield_by_rangeN)__name__
__module____qualname____doc__r9   r<   r;   r:   r   r   r   r   r3   q   s    
	r3   readerc                 C   sp   t |}||}|j}	|	jddd |dur|	j|d |	j| |d |dur5|D ]
}
|j|
d|d q*|jS )a  
    Write a table to a new google sheet.

    The `credentials_or_client` are used to authenticate with the google apis.
    For more info, check `authentication`_. 

    The `spreadsheet` will be the title of the workbook created google sheets.
    If there is a spreadsheet with same title a new one will be created.

    If `worksheet` is specified, the first worksheet in the spreadsheet
    will be renamed to its value.

    The spreadsheet will be shared with all emails in `share_emails` with
    `role` permissions granted. For more info, check `sharing`_. 

    Returns: the spreadsheet key that can be used in `appendgsheet` further.


    .. _sharing: https://developers.google.com/drive/v3/web/manage-sharing

    .. note::
        The `gspread`_ package doesn't support serialization of `date` and 
        `datetime` types yet.

    Example usage::

        >>> from petl import fromcolumns, togsheet
        >>> import gspread # doctest: +SKIP
        >>> client = gspread.service_account() # doctest: +SKIP
        >>> cols = [[0, 1, 2], ['a', 'b', 'c']]
        >>> tbl = fromcolumns(cols)
        >>> togsheet(tbl, client, 'example_spreadsheet') # doctest: +SKIP
    r(   )rowscolsNr#   )table_rangeuser)	perm_typerole)r   creater)   resizeupdate_titleappend_rowsshareid)tabler4   r    r-   r5   share_emailsrL   r   r!   r0   
user_emailr   r   r   togsheet   s   &
rV   c           
      C   sD   t |}t|||}t||d}|r| ntt| }	||	 |jS )a  
    Append a table to an existing google shoot at either a new worksheet
    or the end of an existing worksheet.

    The `credentials_or_client` are used to authenticate with the google apis.
    For more info, check `authentication`_. 

    The `spreadsheet` is the name of the workbook to append to.

    The `worksheet` is the title of the worksheet to append to or create when it
    does not exist yet.

    Set `open_by_key` to `True` in order to treat `spreadsheet` as spreadsheet key.

    Set `include_header` to `True` if you don't want omit fieldnames as the 
    first row appended.

    .. note:: 
        The sheet index cannot be used, and None is not an option.
    T)r   r"   r2   listr   rP   rR   )
rS   r4   r    r-   r   include_headerr   r!   r0   rG   r   r   r   appendgsheet   s   
rY   )F)NNF)NNNrF   )NFF)
__future__r   r   r   petl.util.baser   r   petl.compatr   petl.errorsr   r   r   r"   r2   r6   r3   rV   rY   r   r   r   r   <module>   s&   


2"
7
"
