a
    |f                    @   s  d Z ddlZddlZddlmZmZmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZ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m Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ed
u rddl9m:Z: ede;ee;ef dZ<ede;e
e
e  dZ=ee;ef Z>edddZ?G dd de@ZAG dd dZBdS )zW
gspread.worksheet
~~~~~~~~~~~~~~~~~

This module contains common worksheets' models.

    N)TYPE_CHECKINGAnyCallableDictIterableIteratorListLiteralMappingMutableMappingOptionalSequenceTupleType	TypedDictTypeVarUnion   )Cell)GSpreadException)
HTTPClient
ParamsType)WORKSHEET_DRIVE_URL)DateTimeOption	DimensionGridRangeTypeInsertDataOption	MergeTypePasteOrientation	PasteTypeTValidationConditionTypeValueInputOptionValueRenderOptiona1_range_to_grid_rangea1_to_rowcolabsolute_range_namecast_to_a1_notationcell_list_to_rectcombined_merge_valuesconvert_colors_to_hex_valueconvert_hex_to_colors_dict	fill_gapsfinditemget_a1_from_absolute_rangeis_full_a1_notationnumericise_allrowcol_to_a1
to_recordsT)Spreadsheet
CellFormatrangeformat	BatchData)r6   valuesValueRangeType
ValueRange)boundc                   @   s   e Zd ZU dZi Zeeef ed< ee	e
 eeef e
dddZeedddZeedd	d
Zdee ee dddZdS )r;   a   The class holds the returned values.

    This class inherit the :const:`list` object type.
    It behaves exactly like a list.

    The values are stored in a matrix.

    The property :meth:`gspread.worksheet.ValueRange.major_dimension`
    holds the major dimension of the first list level.

    The inner lists will contain the actual values.

    Examples::

        >>> worksheet.get("A1:B2")
        [
            [
                "A1 value",
                "B1 values",
            ],
            [
                "A2 value",
                "B2 value",
            ]
        ]

        >>> worksheet.get("A1:B2").major_dimension
        ROW

    .. note::

       This class should never be instantiated manually.
       It will be instantiated using the response from the sheet API.
    _json)clsjsonreturnc                 C   s,   | dg }| |}|d |d d|_|S )Nr9   r6   majorDimension)r6   rA   )getr=   )r>   r?   r9   Znew_obj rC   KD:\Projects\storyit_web\backend\venv\Lib\site-packages\gspread/worksheet.py	from_jsonx   s    zValueRange.from_jsonr@   c                 C   s
   | j d S )zThe range of the valuesr6   r=   selfrC   rC   rD   r6      s    zValueRange.rangec                 C   s
   | j d S )zThe major dimension of this range

        Can be one of:

        * ``ROW``: the first list level holds rows of values
        * ``COLUMNS``: the first list level holds columns of values
        rA   rG   rH   rC   rC   rD   major_dimension   s    	zValueRange.major_dimensionN)defaultr@   c                 C   s*   z| d d W S  t y$   | Y S 0 dS )zpReturns the value of a first cell in a range.

        If the range is empty, return the default value.
        r   N)
IndexError)rI   rK   rC   rC   rD   first   s    zValueRange.first)N)__name__
__module____qualname____doc__r=   r   str__annotations__classmethodr   r:   r
   r   rE   propertyr6   rJ   r   rM   rC   rC   rC   rD   r;   R   s   
# 

c                   @   s  e Zd ZdZddeeef ee ee dddZ	eddd	Z
eedd
dZeddddZeedddZeedddZeedddZeedddZeedddZeedddZeedddZeedddZeedddZeedd d!Zeee dd"d#Zee dd$d%Zeee ed&d'd(Zejfeee d)d*d+Z!ejfeeee d,d-d.Z"e#dee$e  d0d1d2Z%ddddd3d3d4e&j'fee ee( ee ee) eeee&e*e+e$e$e  f d5	d6d7Z,ddddd3d3d4e&j'fee ee( ee ee) eeee&e*e+e$e$e  f d5	d8d9Z-d:ddd/g d3d3feee$e  ee ee.e*eef  eee$e/ee*ee0ef f  d;d<d=Z1e$e  dd>d?Z2deee( ee ee) e$e d@dAdBZ3ejfeee$ee*ee0ef   dCdDdEZ4ee*ee0ef e5dFdGdHZ6eee*ee0ef e5dIdJdKZ7e8j9fe$e  e8e:eef dLdMdNZ;ddddd3d3d3e&j+fee ee( ee ee) eeee&e*e+e$e$e  f d5	dOdPZ<de.e ee( ee ee) e$e+ dQdRdSZ=de.e.e  ee eee( ee8 ee ee ee) e5dT	dUdVZ>de.eeef  eee8 ee ee ee) e5dWdXdYZ?e$e@ e5dZd[d\ZAe*e$e ef e5e5d]d^d_ZBdee ee e5d`dadbZCddceDeeEdd f ee e5dedfdgZFee5dhdidjZGee5dkdldmZHe5ddndoZIee5dpdqdrZJeee(e5dsdtduZKeee5dvdwdxZLeee5dydzd{ZMedd|d}d~ZNeddddZOe8j9ddd3fePe*eee0f  e8eeQ ee ee5dddZRe8j9dddfePePe*eee0f   e8eeQ ee ee e5dddZSd:e8j9d3fePe*eee0f  ee8ee5dddZTd:e8j9d3fePePe*eee0f   ee8ee5dddZUd:e8j9d3fePePe*eee0f   ee8ee5dddZVe#g g dd3d3feePe ePe ee eee5dddZWee5dddZXde(eee e5dddZYdeee e5dddZZdeee e5dddZ[e5dddZ\ePe e5dddZ]de^e^e gef e.e  ge_e  f e*ee`jaf eee ee e_e  dddZbdePePe*eee0f   ee ee e$e  dddZcde*ee`jaf ee ee eee  dddZdde*ee`jaf ee ee ee$e  dddZedee ee e5d`ddZfe#dee ed0ddZge5dddZheid eeeeee ee ee d dddZjd!ee ee ee d dddZkee5dddZle#emjnfeeedddZoe#ee5d0ddZpd"ee e$e$e  dddĄZqeedŜddǄZre:eef ddȜddʄZse#eedd˜dd̈́Zte#eedd˜ddτZue:eef ddȜddфZve.e ddddӄZwe#eddŜddՄZxe#eee5d֜dd؄Zyee5dٜddۄZzeee(e5dܜddބZ{eee5dߜddZ|eee5dߜddZ}eee(e5dܜddZ~eee5dߜddZeee5dߜddZe$e5 dddZe$e5 dddZeee(e5dܜddZeee5dߜddZeee5dߜddZeee(e5dܜddZeee5dߜddZeee5dߜddZee5dddZe5dddZe5ddd Zee5dddZe5dddZe5dddZejejfeeeee5ddd	Zejfeeee5d
ddZd#eee.e ee eeedddZdS ($  	WorksheetzUThe class that represents a single sheet in a spreadsheet
    (aka "worksheet").
    Nr3   )spreadsheet
propertiesspreadsheet_idclientc                 C   sJ   |d u sdrt d|d u s&t|ts.t d|| _|| _|| _|| _d S )N zMissing spreadsheet_id parameter, it must be provided with a
                valid spreadsheet ID.
                Please allocate new Worksheet object using method like:
                spreadsheet.get_worksheet(0)
                zMissing HTTP Client, it must be provided with a
                valid instance of type gspread.http_client.HTTPClient .
                Please allocate new Worksheet object using method like:
                spreadsheet.get_worksheet(0)
                )RuntimeError
isinstancer   rY   rZ   _properties_spreadsheet)rI   rW   rX   rY   rZ   rC   rC   rD   __init__   s    zWorksheet.__init__rF   c                 C   s   d | jjt| j| jS )Nz<{} {} id:{}>)r7   	__class__rN   reprtitleidrH   rC   rC   rD   __repr__   s
    zWorksheet.__repr__c                 C   s
   | j d S )zWorksheet ID.sheetIdr^   rH   rC   rC   rD   rd      s    zWorksheet.idc                 C   s   | j S )zParent spreadsheet)r_   rH   rC   rC   rD   rW      s    zWorksheet.spreadsheetc                 C   s
   | j d S )zWorksheet title.rc   rg   rH   rC   rC   rD   rc      s    zWorksheet.titlec                 C   s   t | j| jf S )zWorksheet URL.)r   rY   rd   rH   rC   rC   rD   url   s    zWorksheet.urlc                 C   s
   | j d S )zWorksheet index.indexrg   rH   rC   rC   rD   ri      s    zWorksheet.indexc                 C   s   | j ddS )zWorksheet hidden status.hiddenFr^   rB   rH   rC   rC   rD   isSheetHidden   s    zWorksheet.isSheetHiddenc                 C   s   | j d d S )zNumber of rows.gridPropertiesrowCountrg   rH   rC   rC   rD   	row_count   s    zWorksheet.row_countc                 C   s   | j d d S )zNumber of columns.

        .. warning::

           This value is fetched when opening the worksheet.
           This is not dynamically updated when adding columns, yet.
        rm   columnCountrg   rH   rC   rC   rD   	col_count   s    	zWorksheet.col_countc                 C   s   | j S )zNumber of columns)rq   rH   rC   rC   rD   column_count   s    zWorksheet.column_countc                 C   s   | j d ddS )zNumber of frozen rows.rm   frozenRowCountr   rk   rH   rC   rC   rD   frozen_row_count  s    zWorksheet.frozen_row_countc                 C   s   | j d ddS )zNumber of frozen columns.rm   frozenColumnCountr   rk   rH   rC   rC   rD   frozen_col_count	  s    zWorksheet.frozen_col_countc                 C   s   | j d ddS )zZWhether or not gridlines hidden. Boolean.
        True if hidden. False if shown.
        rm   hideGridlinesFrk   rH   rC   rC   rD   is_gridlines_hidden  s    zWorksheet.is_gridlines_hiddenc                 C   s   |   S )z+Tab color style. Hex with RGB color values.)get_tab_colorrH   rC   rC   rD   	tab_color  s    zWorksheet.tab_colorc                 C   s0   | j di dd}|du r"dS tf i |S )z&Tab color style in hex format. String.tabColorStylergbColorN)r^   rB   r*   )rI   rz   rC   rC   rD   ry     s    zWorksheet.get_tab_color)rU   default_valuer@   c                    s0    j  j}t fdd|d }|||S )zAreturn a property of this worksheet or default value if not foundc                    s   | d d  j kS )NrX   rf   )rd   xrH   rC   rD   <lambda>%      z/Worksheet._get_sheet_property.<locals>.<lambda>sheets)rZ   fetch_sheet_metadatarY   r-   rB   )rI   rU   r}   metaZsheetrC   rH   rD   _get_sheet_property!  s
    zWorksheet._get_sheet_property)labelvalue_render_optionr@   c                 C   s   | j t|d|iS )a  Returns an instance of a :class:`gspread.cell.Cell`.

        :param label: Cell label in A1 notation
                      Letter case is ignored.
        :type label: str
        :param value_render_option: (optional) Determines how values should be
                                    rendered in the output. See
                                    `ValueRenderOption`_ in the Sheets API.
        :type value_render_option: :class:`~gspread.utils.ValueRenderOption`

        .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        Example:

        >>> worksheet.acell('A1')
        <Cell R1C1 "I'm cell A1">
        r   )cellr%   )rI   r   r   rC   rC   rD   acell*  s
    zWorksheet.acell)rowcolr   r@   c                 C   s\   z8| j t|||tjd}t|tr.| }ntdW n tyN   d}Y n0 t|||S )a  Returns an instance of a :class:`gspread.cell.Cell` located at
        `row` and `col` column.

        :param row: Row number.
        :type row: int
        :param col: Column number.
        :type col: int
        :param value_render_option: (optional) Determines how values should be
                                    rendered in the output. See
                                    `ValueRenderOption`_ in the Sheets API.
        :type value_render_option: :class:`~gspread.utils.ValueRenderOption`

        .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        Example:

        >>> worksheet.cell(1, 1)
        <Cell R1C1 "I'm cell A1">

        :rtype: :class:`gspread.cell.Cell`
        )r   return_typez(returned data must be of type ValueRanger[   )	rB   r1   r   r;   r]   rM   r\   KeyErrorr   )rI   r   r   r   datavaluerC   rC   rD   r   D  s    


zWorksheet.cellr[   )namer@   c           	         s   t | j|}| j| j|}d|vrF|dd}d|v rF|dd }t|}|dg }|dd|d	d |d
| j}|d| j	}|dur|8 }|dur| 8 }t
|||d} fddt|D S )a'  Returns a list of :class:`gspread.cell.Cell` objects from a specified range.

        :param name: A string with range value in A1 notation (e.g. 'A1:A5')
                     or the named range to fetch.
        :type name: str

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        :rtype: list

        Example::

            >>> # Using A1 notation
            >>> worksheet.range('A1:B7')
            [<Cell R1C1 "42">, ...]

            >>> # Same with numeric boundaries
            >>> worksheet.range(1, 1, 7, 2)
            [<Cell R1C1 "42">, ...]

            >>> # Named ranges work as well
            >>> worksheet.range('NamedRange')
            [<Cell R1C1 "42">, ...]

            >>> # All values in a single API call
            >>> worksheet.range()
            [<Cell R1C1 'Hi mom'>, ...]

        :r6   r[   !r   r9   startRowIndexr   startColumnIndexendRowIndexendColumnIndexNrowscolsc                    s@   g | ]8\}}t |D ]&\}}t| d  |  d  |dqqS r   )r   r   r   )	enumerater   .0ir   jr   Zcolumn_offset
row_offsetrC   rD   
<listcomp>  s   z#Worksheet.range.<locals>.<listcomp>)r&   rc   rZ   
values_getrY   rB   splitr$   ro   rq   r,   r   )	rI   r   range_labelr   
grid_ranger9   last_rowlast_columnZrect_valuesrC   r   rD   r6   r  s0    %zWorksheet.rangeFT)	
range_namerJ   r   date_time_render_optioncombine_merged_cellsmaintain_size
pad_valuesr   r@   c	           	   
   C   s   | j ||||||||dS )zAlias for :meth:`~gspread.worksheet.Worksheet.get`...

        with ``return_type`` set to ``List[List[Any]]``
        and ``pad_values`` set to ``True``
        (legacy method)
        r   rJ   r   r   r   r   r   r   rB   	rI   r   rJ   r   r   r   r   r   r   rC   rC   rD   
get_values  s    zWorksheet.get_valuesc	           	   
   C   s   | j ||||||||dS )z8Alias to :meth:`~gspread.worksheet.Worksheet.get_values`r   )r   r   rC   rC   rD   get_all_values  s    zWorksheet.get_all_valuesr   )headexpected_headersr   default_blanknumericise_ignore%allow_underscores_in_numeric_literals
empty2zeror@   c                    s   | j |dd}|g gkrg S ||d  ||d }	|du r^tttk}
|
stdnPt|tt|k}|s~tdtfdd|D std	t|t  d
gkrn fdd|	D }	t|	S )a	  Returns a list of dictionaries, all of them having the contents of
        the spreadsheet with the head row as keys and each of these
        dictionaries holding the contents of subsequent rows of cells as
        values.

        This method uses the function :func:`gspread.utils.to_records` to build the resulting
        records. It mainly wraps around the function and handle the simplest use case
        using a header row (default = 1) and the the reste of the entire sheet.

        .. note::

           for any particular use-case, please get your dataset, your headers
           then use the function :func:`gspread.utils.to_records` to build the records.

        Cell values are numericised (strings that can be read as ints or floats
        are converted), unless specified in numericise_ignore

        :param int head: (optional) Determines which row to use as keys,
            starting from 1 following the numeration of the spreadsheet.
        :param list expected_headers: (optional) List of expected headers, they must be unique.

            .. note::

                returned dictionaries will contain all headers even if not included in this list
        :param value_render_option: (optional) Determines how values should
            be rendered in the output. See `ValueRenderOption`_ in
            the Sheets API.
        :type value_render_option: :class:`~gspread.utils.ValueRenderOption`
        :param str default_blank: (optional) Determines which value to use for
            blank cells, defaults to empty string.
        :param list numericise_ignore: (optional) List of ints of indices of
            the columns (starting at 1) to ignore numericising, special use
            of ['all'] to ignore numericising on all columns.
        :param bool allow_underscores_in_numeric_literals: (optional) Allow
            underscores in numeric literals, as introduced in PEP 515
        :param bool empty2zero: (optional) Determines whether empty cells are
            converted to zeros when numericised, defaults to False.


        Examples::

            # Sheet data:
            #      A    B    C
            #
            # 1    A1   B2   C3
            # 2    A6   B7   C8
            # 3    A11  B12  C13

            # Read all rows from the sheet
            >>> worksheet.get_all_records()
            [
                {"A1": "A6", "B2": "B7", "C3": "C8"},
                {"A1": "A11", "B2": "B12", "C3": "C13"}
            ]
        T)r   r   r   Nz`the header row in the worksheet is not unique, try passing 'expected_headers' to get_all_recordsz,the given 'expected_headers' are not uniquesc                 3   s   | ]}| v V  qd S NrC   )r   header)keysrC   rD   	<genexpr>K  r   z,Worksheet.get_all_records.<locals>.<genexpr>z7the given 'expected_headers' contains unknown headers: allc                    s   g | ]}t | qS rC   )r0   )r   r   )r   r   r   r   rC   rD   r   T  s   z-Worksheet.get_all_records.<locals>.<listcomp>)rB   lensetr   r   r2   )rI   r   r   r   r   r   r   r   Zentire_sheetr9   Zheader_row_is_uniqueZexpected_headers_are_uniquerC   )r   r   r   r   r   rD   get_all_records  s>    A

zWorksheet.get_all_recordsc                 C   s   |   S )z2Returns a list of all `Cell` of the current sheet.r6   rH   rC   rC   rD   get_all_cellsa  s    zWorksheet.get_all_cells)r   rJ   r   r   r@   c                 C   sF   z*|  d|||||}|r&|d ng W S  ty@   g  Y S 0 dS )a	  Returns a list of all values in a `row`.

        Empty cells in this list will be rendered as :const:`None`.

        :param int row: Row number (one-based).

        :param str major_dimension: (optional) The major dimension of the
            values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS").
            Defaults to Dimension.rows
        :type major_dimension: :class:`~gspread.utils.Dimension`

        :param value_render_option: (optional) Determines how values should
            be rendered in the output. See `ValueRenderOption`_ in
            the Sheets API.

            Possible values are:

            ``ValueRenderOption.formatted``
                (default) Values will be calculated and formatted according
                to the cell's formatting. Formatting is based on the
                spreadsheet's locale, not the requesting user's locale.

            ``ValueRenderOption.unformatted``
                Values will be calculated, but not formatted in the reply.
                For example, if A1 is 1.23 and A2 is =A1 and formatted as
                currency, then A2 would return the number 1.23.

            ``ValueRenderOption.formula``
                Values will not be calculated. The reply will include
                the formulas. For example, if A1 is 1.23 and A2 is =A1 and
                formatted as currency, then A2 would return "=A1".

            .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        :type value_render_option: :class:`~gspread.utils.ValueRenderOption`

        :param date_time_render_option: (optional) How dates, times, and
            durations should be represented in the output.

            Possible values are:

            ``DateTimeOption.serial_number``
                (default) Instructs date, time, datetime, and duration fields
                to be output as doubles in "serial number" format,
                as popularized by Lotus 1-2-3.

            ``DateTimeOption.formatted_string``
                Instructs date, time, datetime, and duration fields to be output
                as strings in their given number format
                (which depends on the spreadsheet locale).

            .. note::

                This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``.

            The default ``date_time_render_option`` is ``DateTimeOption.serial_number``.
        :type date_time_render_option: :class:`~gspread.utils.DateTimeOption`
        zA{}:{}r   N)rB   r7   r   )rI   r   rJ   r   r   r   rC   rC   rD   
row_valuesf  s    A
zWorksheet.row_values)r   r   r@   c                 C   sp   t d|}d||dd }t| j|}| jj| j||tjdd}z|d d W S  t	yj   g  Y S 0 dS )	a  Returns a list of all values in column `col`.

        Empty cells in this list will be rendered as :const:`None`.

        :param int col: Column number (one-based).
        :param str value_render_option: (optional) Determines how values should
            be rendered in the output. See `ValueRenderOption`_ in
            the Sheets API.
        :type value_render_option: :class:`~gspread.utils.ValueRenderOption`

        .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption
        r   {}:{}N)valueRenderOptionrA   paramsr9   r   )
r1   r7   r&   rc   rZ   r   rY   r   r   r   )rI   r   r   Zstart_labelr   r   r   rC   rC   rD   
col_values  s    
	zWorksheet.col_values)r   r   r@   c                 C   s   | j t|d|iS )zUpdates the value of a cell.

        :param str label: Cell label in A1 notation.
        :param value: New value.

        Example::

            worksheet.update_acell('A1', '42')
        r   )update_cellr%   )rI   r   r   rC   rC   rD   update_acell  s    
zWorksheet.update_acell)r   r   r   r@   c                 C   s:   t | jt||}| jj| j|dtjid|ggid}|S )zUpdates the value of a cell.

        :param int row: Row number.
        :param int col: Column number.
        :param value: New value.

        Example::

            worksheet.update_cell(1, 1, '42')
        valueInputOptionr9   r   body)r&   rc   r1   rZ   values_updaterY   r"   user_entered)rI   r   r   r   r   r   rC   rC   rD   r     s    
zWorksheet.update_cell)	cell_listvalue_input_optionr@   c                 C   s   t |}ttdd |D tdd |D }ttdd |D tdd |D }t| jd||}| jj| j	|d|id|id	}|S )
a  Updates many cells at once.

        :param list cell_list: List of :class:`gspread.cell.Cell` objects to update.
        :param  value_input_option: (optional) How the input data should be
            interpreted. Possible values are:

            ``ValueInputOption.raw``
                (default) The values the user has entered will not be parsed and will be
                stored as-is.

            ``ValueInputOption.user_entered``
                The values will be parsed as if the user typed them into the
                UI. Numbers will stay as numbers, but strings may be converted
                to numbers, dates, etc. following the same rules that are
                applied when entering text into a cell via
                the Google Sheets UI.

            See `ValueInputOption`_ in the Sheets API.

        :type value_input_option: :namedtuple:`~gspread.utils.ValueInputOption`

        .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption

        Example::

            # Select a range
            cell_list = worksheet.range('A1:C7')

            for cell in cell_list:
                cell.value = 'O_o'

            # Update in batch
            worksheet.update_cells(cell_list)
        c                 s   s   | ]}|j V  qd S r   r   r   crC   rC   rD   r   %  r   z)Worksheet.update_cells.<locals>.<genexpr>c                 s   s   | ]}|j V  qd S r   r   r   rC   rC   rD   r   %  r   c                 s   s   | ]}|j V  qd S r   r   r   rC   rC   rD   r   '  r   c                 s   s   | ]}|j V  qd S r   r   r   rC   rC   rD   r   '  r   r   r   r9   r   )
r(   r1   minmaxr&   rc   r7   rZ   r   rY   )rI   r   r   Zvalues_rectstartendr   r   rC   rC   rD   update_cells  s    ' &zWorksheet.update_cellsc	                    s  t j }	|||d}
jjj|	|
d}|dg g}|du rhzt|}W n tyf   g g}Y n0 |du r&jj}t	fdd|d }|dg }t
 fd	d
|D rt	 fdd|}|di }n. durt }t|}n|di di }t|||dd|ddd} p.d |du rt rt }t|}|d |d  }|d |d  }t|||d}|tju r||d< t|S |tju r|S tddS )az  Reads values of a single range or a cell of a sheet.

        Returns a ValueRange (list of lists) containing all values from a specified range or cell

        By default values are returned as strings. See ``value_render_option``
        to change the default format.

        :param str range_name: (optional) Cell range in the A1 notation or
            a named range. If not specified the method returns values from all non empty cells.

        :param str major_dimension: (optional) The major dimension of the
            values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS").
            Defaults to Dimension.rows
        :type major_dimension: :class:`~gspread.utils.Dimension`

        :param value_render_option: (optional) Determines how values should
            be rendered in the output. See `ValueRenderOption`_ in
            the Sheets API.

            Possible values are:

            ``ValueRenderOption.formatted``
                (default) Values will be calculated and formatted according
                to the cell's formatting. Formatting is based on the
                spreadsheet's locale, not the requesting user's locale.

            ``ValueRenderOption.unformatted``
                Values will be calculated, but not formatted in the reply.
                For example, if A1 is 1.23 and A2 is =A1 and formatted as
                currency, then A2 would return the number 1.23.

            ``ValueRenderOption.formula``
                Values will not be calculated. The reply will include
                the formulas. For example, if A1 is 1.23 and A2 is =A1 and
                formatted as currency, then A2 would return "=A1".

            .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        :type value_render_option: :class:`~gspread.utils.ValueRenderOption`

        :param str date_time_render_option: (optional) How dates, times, and
            durations should be represented in the output.

            Possible values are:

            ``DateTimeOption.serial_number``
                (default) Instructs date, time, datetime, and duration fields
                to be output as doubles in "serial number" format,
                as popularized by Lotus 1-2-3.

            ``DateTimeOption.formatted_string``
                Instructs date, time, datetime, and duration fields to be output
                as strings in their given number format
                (which depends on the spreadsheet locale).

            .. note::

                This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``.

            The default ``date_time_render_option`` is ``DateTimeOption.serial_number``.
        :type date_time_render_option: :class:`~gspread.utils.DateTimeOption`

        :param bool combine_merged_cells: (optional) If True, then all cells that
            are part of a merged cell will have the same value as the top-left
            cell of the merged cell. Defaults to False.

            .. warning::

                Setting this to True will cause an additional API request to be
                made to retrieve the values of all merged cells.

        :param bool maintain_size: (optional) If True, then the returned values
            will have the same size as the requested range_name. Defaults to False.

        :param bool pad_values: (optional) If True, then empty cells will be
            filled with empty strings. Defaults to False.

            .. warning::

                    The returned array will not be rectangular unless this is set to True. If this is a problem, see also `maintain_size`.

        :param GridRangeType return_type: (optional) The type of object to return.
            Defaults to :class:`gspread.utils.GridRangeType.ValueRange`.
            The other option is `gspread.utils.GridRangeType.ListOfLists`.

        :rtype: :class:`gspread.worksheet.ValueRange`

        .. versionadded:: 3.3

        Examples::

            # Return all values from the sheet
            worksheet.get()

            # Return value of 'A1' cell
            worksheet.get('A1')

            # Return values of 'A1:B2' range
            worksheet.get('A1:B2')

            # Return all values from columns "A" and "B"
            worksheet.get('A:B')

            # Return values of 'my_range' named range
            worksheet.get('my_range')

            # Return unformatted values (e.g. numbers as numbers)
            worksheet.get('A2:B4', value_render_option=ValueRenderOption.unformatted)

            # Return cell values without calculating formulas
            worksheet.get('A2:B4', value_render_option=ValueRenderOption.formula)
        rA   r   ZdateTimeRenderOptionr   r9   Tc                    s   | d d  j kS )NrX   rc   )rc   r~   rH   rC   rD   r     r   zWorksheet.get.<locals>.<lambda>r   ZnamedRangesc                 3   s$   | ]}| d r |d  kV  qdS )r   Nr   )r   Zss_namedRanger   rC   rD   r     s   
z Worksheet.get.<locals>.<genexpr>c                    s   | d  kS )Nr   rC   r~   r   rC   rD   r     r   r6   NZbasicFilterr   r   r   )Zworksheet_metadatar9   start_row_indexZstart_col_indexr[   r   r   r   z4return_type must be either ValueRange or ListOfLists)r&   rc   rZ   r   rY   rB   r,   r   r   r-   anyr.   r$   r)   r/   r   r;   rE   ListOfLists
ValueError)rI   r   rJ   r   r   r   r   r   r   Zget_range_namer   responser9   Zspreadsheet_metaZworksheet_metaZnamed_rangesZss_named_ranger   Za1Za1_ranger   r   rC   )r   rI   rD   rB   4  sf    |






zWorksheet.get)rangesrJ   r   r   r@   c                    sD    fdd|D }|||d} j j j||d}dd |d D S )a
  Returns one or more ranges of values from the sheet.

        :param list ranges: List of cell ranges in the A1 notation or named
            ranges.

        :param str major_dimension: (optional) The major dimension of the
            values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS").
            Defaults to Dimension.rows
        :type major_dimension: :class:`~gspread.utils.Dimension`

        :param value_render_option: (optional) Determines how values should
            be rendered in the output. See `ValueRenderOption`_ in
            the Sheets API.

            Possible values are:

            ``ValueRenderOption.formatted``
                (default) Values will be calculated and formatted according
                to the cell's formatting. Formatting is based on the
                spreadsheet's locale, not the requesting user's locale.

            ``ValueRenderOption.unformatted``
                Values will be calculated, but not formatted in the reply.
                For example, if A1 is 1.23 and A2 is =A1 and formatted as
                currency, then A2 would return the number 1.23.

            ``ValueRenderOption.formula``
                Values will not be calculated. The reply will include
                the formulas. For example, if A1 is 1.23 and A2 is =A1 and
                formatted as currency, then A2 would return "=A1".

            .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        :type value_render_option: :class:`~gspread.utils.ValueRenderOption`

        :param str date_time_render_option: (optional) How dates, times, and
            durations should be represented in the output.

            Possible values are:

            ``DateTimeOption.serial_number``
                (default) Instructs date, time, datetime, and duration fields
                to be output as doubles in "serial number" format,
                as popularized by Lotus 1-2-3.

            ``DateTimeOption.formatted_string``
                Instructs date, time, datetime, and duration fields to be output
                as strings in their given number format
                (which depends on the spreadsheet locale).

            .. note::

                This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``.

            The default ``date_time_render_option`` is ``DateTimeOption.serial_number``.
        :type date_time_render_option: :class:`~gspread.utils.DateTimeOption`

        .. versionadded:: 3.3

        Examples::

            # Read values from 'A1:B2' range and 'F12' cell
            worksheet.batch_get(['A1:B2', 'F12'])
        c                    s   g | ]}|rt  j|qS rC   r&   rc   )r   rrH   rC   rD   r   @  r   z'Worksheet.batch_get.<locals>.<listcomp>r   )r   r   c                 S   s   g | ]}t |qS rC   )r;   rE   )r   r   rC   rC   rD   r   L  r   ZvalueRanges)rZ   Zvalues_batch_getrY   )rI   r   rJ   r   r   r   r   rC   rH   rD   	batch_get  s    GzWorksheet.batch_get)	r9   r   rawrJ   r   include_values_in_responseresponse_value_render_option response_date_time_render_optionr@   c	                 C   s   t |ttfr2t |tr2tjdtdd || }}t| j|}	|sV|du rPt	j
nt	j}||||d}
| jj| j|	|
||dd}|S )ap  Sets values in a cell range of the sheet.

        :param list values: The data to be written in a matrix format.
        :param str range_name: (optional) The A1 notation of the values
            to update.

        :param bool raw: The values will not be parsed by Sheets API and will
            be stored as-is. For example, formulas will be rendered as plain
            strings. Defaults to ``True``. This is a shortcut for
            the ``value_input_option`` parameter.

        :param str major_dimension: (optional) The major dimension of the
            values. `Dimension.rows` ("ROWS") or `Dimension.cols` ("COLUMNS").
            Defaults to Dimension.rows
        :type major_dimension: :class:`~gspread.utils.Dimension`

        :param str value_input_option: (optional) How the input data should be
            interpreted. Possible values are:

            ``ValueInputOption.raw``
                (default) The values the user has entered will not be parsed and will be
                stored as-is.

            ``ValueInputOption.user_entered``
                The values will be parsed as if the user typed them into the
                UI. Numbers will stay as numbers, but strings may be converted
                to numbers, dates, etc. following the same rules that are
                applied when entering text into a cell via
                the Google Sheets UI.

        :type value_input_option: :class:`~gspread.utils.ValueInputOption`

        :param response_value_render_option: (optional) Determines how values should
            be rendered in the output. See `ValueRenderOption`_ in
            the Sheets API.

            Possible values are:

            ``ValueRenderOption.formatted``
                (default) Values will be calculated and formatted according
                to the cell's formatting. Formatting is based on the
                spreadsheet's locale, not the requesting user's locale.

            ``ValueRenderOption.unformatted``
                Values will be calculated, but not formatted in the reply.
                For example, if A1 is 1.23 and A2 is =A1 and formatted as
                currency, then A2 would return the number 1.23.

            ``ValueRenderOption.formula``
                Values will not be calculated. The reply will include
                the formulas. For example, if A1 is 1.23 and A2 is =A1 and
                formatted as currency, then A2 would return "=A1".

            .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        :type response_value_render_option: :class:`~gspread.utils.ValueRenderOption`

        :param str response_date_time_render_option: (optional) How dates, times, and
            durations should be represented in the output.

            Possible values are:

            ``DateTimeOption.serial_number``
                (default) Instructs date, time, datetime, and duration fields
                to be output as doubles in "serial number" format,
                as popularized by Lotus 1-2-3.

            ``DateTimeOption.formatted_string``
                Instructs date, time, datetime, and duration fields to be output
                as strings in their given number format
                (which depends on the spreadsheet locale).

            .. note::

                This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``.

            The default ``date_time_render_option`` is ``DateTimeOption.serial_number``.
        :type date_time_render_option: :class:`~gspread.utils.DateTimeOption`

        Examples::

            # Sets 'Hello world' in 'A2' cell
            worksheet.update([['Hello world']], 'A2')

            # Updates cells A1, B1, C1 with values 42, 43, 44 respectively
            worksheet.update([[42, 43, 44]])

            # Updates A2 and A3 with values 42 and 43
            # Note that update range can be bigger than values array
            worksheet.update([[42], [43]], 'A2:B4')

            # Add a formula
            worksheet.update([['=SUM(A1:A4)']], 'A5', raw=False)

            # Update 'my_range' named range with values 42 and 43
            worksheet.update([[42], [43]], 'my_range')

            # Note: named ranges are defined in the scope of
            # a spreadsheet, so even if `my_range` does not belong to
            # this sheet it is still updated

        .. versionadded:: 3.3
        zThe order of arguments in worksheet.update() has changed. Please pass values first and range_name secondor used named arguments (range_name=, values=)   )
stacklevelT)r   includeValuesInResponseresponseValueRenderOptionresponseDateTimeRenderOption)r9   rA   r   )r]   listtuplerR   warningswarnDeprecationWarningr&   rc   r"   r   r   rZ   r   rY   )rI   r9   r   r   rJ   r   r   r   r   Zfull_range_namer   r   rC   rC   rD   updateN  s.    r
zWorksheet.update)r   r   r   r   r   r   r@   c           
      C   s\   |s|du rt jnt j}|D ]}t| j|d |d< q|||||d}| jj| j|d}	|	S )aH  Sets values in one or more cell ranges of the sheet at once.

        :param list data: List of dictionaries in the form of
            `{'range': '...', 'values': [[.., ..], ...]}` where `range`
            is a target range to update in A1 notation or a named range,
            and `values` is a list of lists containing new values.

        :param str value_input_option: (optional) How the input data should be
            interpreted. Possible values are:

            * ``ValueInputOption.raw``

              The values the user has entered will not be parsed and will be
              stored as-is.

            * ``ValueInputOption.user_entered``

              The values will be parsed as if the user typed them into the
              UI. Numbers will stay as numbers, but strings may be converted
              to numbers, dates, etc. following the same rules that are
              applied when entering text into a cell via
              the Google Sheets UI.

        :type value_input_option: :class:`~gspread.utils.ValueInputOption`

        :param response_value_render_option: (optional) Determines how values should
            be rendered in the output. See `ValueRenderOption`_ in
            the Sheets API.

            Possible values are:

            ``ValueRenderOption.formatted``
                (default) Values will be calculated and formatted according
                to the cell's formatting. Formatting is based on the
                spreadsheet's locale, not the requesting user's locale.

            ``ValueRenderOption.unformatted``
                Values will be calculated, but not formatted in the reply.
                For example, if A1 is 1.23 and A2 is =A1 and formatted as
                currency, then A2 would return the number 1.23.

            ``ValueRenderOption.formula``
                Values will not be calculated. The reply will include
                the formulas. For example, if A1 is 1.23 and A2 is =A1 and
                formatted as currency, then A2 would return "=A1".

            .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        :type response_value_render_option: :class:`~gspread.utils.ValueRenderOption`

        :param str response_date_time_render_option: (optional) How dates, times, and
            durations should be represented in the output.

            Possible values are:

            ``DateTimeOption.serial_number``
                (default) Instructs date, time, datetime, and duration fields
                to be output as doubles in "serial number" format,
                as popularized by Lotus 1-2-3.

            ``DateTimeOption.formatted_string``
                Instructs date, time, datetime, and duration fields to be output
                as strings in their given number format
                (which depends on the spreadsheet locale).

            .. note::

                This is ignored if ``value_render_option`` is ``ValueRenderOption.formatted``.

            The default ``date_time_render_option`` is ``DateTimeOption.serial_number``.
        :type date_time_render_option: :class:`~gspread.utils.DateTimeOption`

        Examples::

            worksheet.batch_update([{
                'range': 'A1:B1',
                'values': [['42', '43']],
            }, {
                'range': 'my_range',
                'values': [['44', '45']],
            }])

            # Note: named ranges are defined in the scope of
            # a spreadsheet, so even if `my_range` does not belong to
            # this sheet it is still updated

        .. versionadded:: 3.3
        Tr6   )r   r   r   r   r   r   )r"   r   r   r&   rc   rZ   Zvalues_batch_updaterY   )
rI   r   r   r   r   r   r   r9   r   r   rC   rC   rD   batch_update  s    azWorksheet.batch_update)formatsr@   c                 C   sn   dg i}|D ]P}|d }|d }t || j}dd|  }|d d|d|i|di q| j| j|S )	a  Formats cells in batch.

        :param list formats: List of ranges to format and the new format to apply
            to each range.

            The list is composed of dict objects with the following keys/values:

            * range : A1 range notation
            * format : a valid dict object with the format to apply
              for that range see `CellFormat`_ in the Sheets API for available fields.

        .. _CellFormat: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#cellformat

        Examples::

            # Format the range ``A1:C1`` with bold text
            # and format the range ``A2:C2`` a font size of 16

            formats = [
                {
                    "range": "A1:C1",
                    "format": {
                        "textFormat": {
                            "bold": True,
                        },
                    },
                },
                {
                    "range": "A2:C2",
                    "format": {
                        "textFormat": {
                            "fontSize": 16,
                        },
                    },
                },
            ]
            worksheet.batch_format(formats)

        .. versionadded:: 5.4
        requestsr6   r7   zuserEnteredFormat(%s),Z
repeatCellZuserEnteredFormat)r6   r   fields)r$   rd   joinr   appendrZ   r   rY   )rI   r   r   r7   r   Zcell_formatr   r   rC   rC   rD   batch_formatV  s     ,
zWorksheet.batch_format)r   r7   r@   c                    s2   t |tr|}n|g} fdd|D }| |S )a  Format a list of ranges with the given format.

        :param str|list ranges: Target ranges in the A1 notation.
        :param dict format: Dictionary containing the fields to update.
            See `CellFormat`_ in the Sheets API for available fields.

        Examples::

            # Set 'A4' cell's text format to bold
            worksheet.format("A4", {"textFormat": {"bold": True}})

            # Set 'A1:D4' and 'A10:D10' cells's text format to bold
            worksheet.format(["A1:D4", "A10:D10"], {"textFormat": {"bold": True}})

            # Color the background of 'A2:B2' cell range in black,
            # change horizontal alignment, text color and font size
            worksheet.format("A2:B2", {
                "backgroundColor": {
                  "red": 0.0,
                  "green": 0.0,
                  "blue": 0.0
                },
                "horizontalAlignment": "CENTER",
                "textFormat": {
                  "foregroundColor": {
                    "red": 1.0,
                    "green": 1.0,
                    "blue": 1.0
                  },
                  "fontSize": 12,
                  "bold": True
                }
            })

        .. versionadded:: 3.3
        c                    s   g | ]}t | d qS )r5   )r4   r   r6   r7   rC   rD   r     r   z$Worksheet.format.<locals>.<listcomp>)r]   r   r   )rI   r   r7   Z
range_listr   rC   r   rD   r7     s
    (
zWorksheet.format)r   r   r@   c                 C   s   i }|dur||d< |dur$||d< |s0t dddd | D }dd	| j|d
|digi}| j| j|}|dur|| jd d< |dur|| jd d< |S )zResizes the worksheet. Specify one of ``rows`` or ``cols``.

        :param int rows: (optional) New number of rows.
        :param int cols: (optional) New number columns.
        Nrn   rp   ,Either 'rows' or 'cols' should be specified.r   c                 s   s   | ]}d | V  qdS zgridProperties/%sNrC   r   prC   rC   rD   r     r   z#Worksheet.resize.<locals>.<genexpr>r   updateSheetPropertiesrf   rm   rX   r   rm   	TypeErrorr   r   rd   rZ   r   rY   r^   rI   r   r   Zgrid_propertiesr   r   resrC   rC   rD   resize  s0    zWorksheet.resizer   )ascdes)specsr6   r@   c                G   s   |r,| d\}}t|\}}t|\}}n&| jd ddd }d}| j}| j}| j|d ||d |d}	t }
|D ]D\}}|dkrd}n|d	krd
}ntd|d |d}|
	| qvdd|	|
digi}| j
| j|}|S )a  Sorts worksheet using given sort orders.

        :param list specs: The sort order per column. Each sort order
            represented by a tuple where the first element is a column index
            and the second element is the order itself: 'asc' or 'des'.
        :param str range: The range to sort in A1 notation. By default sorts
            the whole sheet excluding frozen rows.

        Example::

            # Sort sheet A -> Z by column 'B'
            wks.sort((2, 'asc'))

            # Sort range A2:G8 basing on column 'G' A -> Z
            # and column 'B' Z -> A
            wks.sort((7, 'asc'), (2, 'des'), range='A2:G8')

        .. versionadded:: 3.4
        r   rm   rs   r   r   )rf   r   r   r   r   r  Z	ASCENDINGr  Z
DESCENDINGz8Either 'asc' or 'des' should be specified as sort order.)ZdimensionIndexZ	sortOrderr   Z	sortRange)r6   Z	sortSpecs)r   r%   r^   rB   ro   rq   rd   r   r   r   rZ   r   rY   )rI   r6   r  Zstart_a1Zend_a1Z	start_rowZ	start_colZend_rowZend_colZrequest_rangeZrequest_sort_specsr   orderZrequest_orderZrequest_sort_specr   r   rC   rC   rD   sort  sJ    zWorksheet.sort)rc   r@   c                 C   s:   dd| j |dddigi}| j| j|}|| jd< |S )zGRenames the worksheet.

        :param str title: A new title.
        r   r  )rf   rc   rc   r  rd   rZ   r   rY   r^   )rI   rc   r   r   rC   rC   rD   update_title:  s    

zWorksheet.update_title)colorr@   c                 C   sJ   t |}dd| jd|idddigi}| j| j|}d|i| jd< |S )zChanges the worksheet's tab color.
        Use clear_tab_color() to remove the color.

        :param str color:  Hex color value.
        r   r  r|   rf   r{   r{   r  )r+   rd   rZ   r   rY   r^   )rI   r  Z
color_dictr   r   rC   rC   rD   update_tab_colorN  s    zWorksheet.update_tab_colorc                 C   s@   dd| j ddidddigi}| j| j|}| jd |S )z[Clears the worksheet's tab color.
        Use update_tab_color() to set the color.
        r   r  r|   Nr  r{   r  )rd   rZ   r   rY   r^   pop)rI   r   r   rC   rC   rD   clear_tab_colorl  s    zWorksheet.clear_tab_color)ri   r@   c                 C   s:   dd| j |dddigi}| j| j|}|| jd< |S )a  Updates the ``index`` property for the worksheet.

        See the `Sheets API documentation
        <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#sheetproperties>`_
        for information on how updating the index property affects the order of worksheets
        in a spreadsheet.

        To reorder all worksheets in a spreadsheet, see `Spreadsheet.reorder_worksheets`.

        .. versionadded:: 3.4
        r   r  )rf   ri   ri   r  r  )rI   ri   r   r  rC   rC   rD   update_index  s    

zWorksheet.update_index)start_index	end_index	dimensionr@   c                 C   s.   ddd| j |||diigi}| j| j|S )a  Updates the size of rows or columns in the  worksheet.

        Index start from 0

        :param start_index: The index (inclusive) to begin resizing
        :param end_index: The index (exclusive) to finish resizing
        :param dimension: Specifies whether to resize the row or column
        :type major_dimension: :class:`~gspread.utils.Dimension`


        .. versionadded:: 5.3.3
        r   ZautoResizeDimensions
dimensionsrf   r  Z
startIndexZendIndexrd   rZ   r   rY   )rI   r  r  r  r   rC   rC   rD   _auto_resize  s    zWorksheet._auto_resize)start_column_indexend_column_indexr@   c                 C   s   |  ||tjS )a3  Updates the size of rows or columns in the  worksheet.

        Index start from 0

        :param start_column_index: The index (inclusive) to begin resizing
        :param end_column_index: The index (exclusive) to finish resizing


        .. versionadded:: 3.4
        .. versionchanged:: 5.3.3
        )r   r   r   )rI   r!  r"  rC   rC   rD   columns_auto_resize  s    zWorksheet.columns_auto_resize)r   end_row_indexr@   c                 C   s   |  ||tjS )a  Updates the size of rows or columns in the  worksheet.

        Index start from 0

        :param start_row_index: The index (inclusive) to begin resizing
        :param end_row_index: The index (exclusive) to finish resizing


        .. versionadded:: 5.3.3
        )r   r   r   )rI   r   r$  rC   rC   rD   rows_auto_resize  s    zWorksheet.rows_auto_resize)r   r@   c                 C   s   | j | j| d dS )zjAdds rows to worksheet.

        :param rows: Number of new rows to add.
        :type rows: int

        )r   N)r  ro   )rI   r   rC   rC   rD   add_rows  s    zWorksheet.add_rows)r   r@   c                 C   s   | j | j| d dS )zpAdds columns to worksheet.

        :param cols: Number of new columns to add.
        :type cols: int

        )r   N)r  rq   )rI   r   rC   rC   rD   add_cols  s    zWorksheet.add_cols)r9   r   insert_data_optiontable_ranger   r@   c                 C   s   | j |g||||dS )a"  Adds a row to the worksheet and populates it with values.

        Widens the worksheet if there are more values than columns.

        :param list values: List of values for the new row.
        :param value_input_option: (optional) Determines how the input data
            should be interpreted. See `ValueInputOption`_ in the Sheets API
            reference.
        :type value_input_option: :class:`~gspread.utils.ValueInputOption`
        :param str insert_data_option: (optional) Determines how the input data
            should be inserted. See `InsertDataOption`_ in the Sheets API
            reference.
        :param str table_range: (optional) The A1 notation of a range to search
            for a logical table of data. Values are appended after the last row
            of the table. Examples: ``A1`` or ``B2:D4``
        :param bool include_values_in_response: (optional) Determines if the
            update response should include the values of the cells that were
            appended. By default, responses do not include the updated values.

        .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption
        .. _InsertDataOption: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#InsertDataOption

        )r   r(  r)  r   )append_rows)rI   r9   r   r(  r)  r   rC   rC   rD   
append_row  s    zWorksheet.append_rowc                 C   sV   t | j|}|||d}d|i}| j| j|||}	t|}
| jd d  |
7  < |	S )a  Adds multiple rows to the worksheet and populates them with values.

        Widens the worksheet if there are more values than columns.

        :param list values: List of rows each row is List of values for
            the new row.
        :param value_input_option: (optional) Determines how input data
            should be interpreted. Possible values are ``ValueInputOption.raw``
            or ``ValueInputOption.user_entered``.
            See `ValueInputOption`_ in the Sheets API.
        :type value_input_option: :class:`~gspread.utils.ValueInputOption`
        :param str insert_data_option: (optional) Determines how the input data
            should be inserted. See `InsertDataOption`_ in the Sheets API
            reference.
        :param str table_range: (optional) The A1 notation of a range to search
            for a logical table of data. Values are appended after the last row
            of the table. Examples: ``A1`` or ``B2:D4``
        :param bool include_values_in_response: (optional) Determines if the
            update response should include the values of the cells that were
            appended. By default, responses do not include the updated values.

        .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption
        .. _InsertDataOption: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#InsertDataOption
        )r   ZinsertDataOptionr   r9   rm   rn   )r&   rc   rZ   values_appendrY   r   r^   )rI   r9   r   r(  r)  r   r   r   r   r  num_new_rowsrC   rC   rD   r*    s     zWorksheet.append_rows)r9   ri   r   inherit_from_beforer@   c                 C   s   | j |g|||dS )a  Adds a row to the worksheet at the specified index and populates it
        with values.

        Widens the worksheet if there are more values than columns.

        :param list values: List of values for the new row.
        :param int index: (optional) Offset for the newly inserted row.
        :param str value_input_option: (optional) Determines how input data
            should be interpreted. Possible values are ``ValueInputOption.raw``
            or ``ValueInputOption.user_entered``.
            See `ValueInputOption`_ in the Sheets API.
        :type value_input_option: :class:`~gspread.utils.ValueInputOption`
        :param bool inherit_from_before: (optional) If True, the new row will
            inherit its properties from the previous row. Defaults to False,
            meaning that the new row acquires the properties of the row
            immediately after it.

            .. warning::

               `inherit_from_before` must be False when adding a row to the top
               of a spreadsheet (`index=1`), and must be True when adding to
               the bottom of the spreadsheet.

        .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption
        )r   r.  )insert_rows)rI   r9   ri   r   r.  rC   rC   rD   
insert_rowE  s     zWorksheet.insert_row)r9   r   r   r.  r@   c                 C   s   d| j v rtd|r&|dkr&tddd| jtj|d t|| d d|digi}| j| j| t	| j d	| }d
|i}tj|d}| j
| j|||}	t|}
| jd d  |
7  < |	S )a  Adds multiple rows to the worksheet at the specified index and
        populates them with values.

        :param list values: List of row lists. a list of lists, with the lists
            each containing one row's values. Widens the worksheet if there are
            more values than columns.
        :param int row: Start row to update (one-based). Defaults to 1 (one).
        :param str value_input_option: (optional) Determines how input data
            should be interpreted. Possible values are ``ValueInputOption.raw``
            or ``ValueInputOption.user_entered``.
            See `ValueInputOption`_ in the Sheets API.
        :type value_input_option: :class:`~gspread.utils.ValueInputOption`
        :param bool inherit_from_before: (optional) If true, new rows will
            inherit their properties from the previous row. Defaults to False,
            meaning that new rows acquire the properties of the row immediately
            after them.

            .. warning::

               `inherit_from_before` must be False when adding rows to the top
               of a spreadsheet (`row=1`), and must be True when adding to
               the bottom of the spreadsheet.
        r   ztcan't insert row in worksheet with colon ':' in its name. See issue: https://issuetracker.google.com/issues/36761154r   zTinherit_from_before cannot be used when inserting row(s) at the top of a spreadsheetr   insertDimensionr  r6   ZinheritFromBeforezA%sr   rA   r9   rm   rn   )rc   r   rd   r   r   r   rZ   r   rY   r&   r,  r^   )rI   r9   r   r   r.  insert_dimension_bodyr   r   r   r  r-  rC   rC   rD   r/  l  s8    !
zWorksheet.insert_rows)r9   r   r   r.  r@   c                 C   s   |r|dkrt ddd| jtj|d t|| d d|digi}| j| j| t| j	t
d|}d|i}tj|d}| j| j|||}	t|}
| jd	 d
  |
7  < |	S )a  Adds multiple new cols to the worksheet at specified index and
        populates them with values.

        :param list values: List of col lists. a list of lists, with the lists
            each containing one col's values. Increases the number of rows
            if there are more values than columns.
        :param int col: Start col to update (one-based). Defaults to 1 (one).
        :param str value_input_option: (optional) Determines how input data
            should be interpreted. Possible values are ``ValueInputOption.raw``
            or ``ValueInputOption.user_entered``.
            See `ValueInputOption`_ in the Sheets API.
        :type value_input_option: :class:`~gspread.utils.ValueInputOption`
        :param bool inherit_from_before: (optional) If True, new columns will
            inherit their properties from the previous column. Defaults to
            False, meaning that new columns acquire the properties of the
            column immediately after them.

            .. warning::

               `inherit_from_before` must be False if adding at the left edge
               of a spreadsheet (`col=1`), and must be True if adding at the
               right edge of the spreadsheet.
        r   z]inherit_from_before cannot be used when inserting column(s) at the left edge of a spreadsheetr   r1  r  r2  r   r3  rm   rp   )r   rd   r   r   r   rZ   r   rY   r&   rc   r1   r,  r^   )rI   r9   r   r   r.  r4  r   r   r   r  Znum_new_colsrC   rC   rD   insert_cols  s0    zWorksheet.insert_cols)r   editor_users_emailseditor_groups_emailsdescriptionwarning_onlyrequesting_user_can_editr@   c           	   
   C   sH   t || j}ddd|||||r"dn||ddiigi}| j| j|S )a=  Add protected range to the sheet. Only the editors can edit
        the protected range.

        Google API will automatically add the owner of this SpreadSheet.
        The list ``editor_users_emails`` must at least contain the e-mail
        address used to open that SpreadSheet.

        ``editor_users_emails`` must only contain e-mail addresses
        who already have a write access to the spreadsheet.

        :param str name: A string with range value in A1 notation,
            e.g. 'A1:A5'.

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        For both A1 and numeric notation:

        :param list editor_users_emails: The email addresses of
            users with edit access to the protected range.
            This must include your e-mail address at least.
        :param list editor_groups_emails: (optional) The email addresses of
            groups with edit access to the protected range.
        :param str description: (optional) Description for the protected
            ranges.
        :param boolean warning_only: (optional) When true this protected range
            will show a warning when editing. Defaults to ``False``.
        :param boolean requesting_user_can_edit: (optional) True if the user
            who requested this protected range can edit the protected cells.
            Defaults to ``False``.
        r   ZaddProtectedRangeZprotectedRangeN)Zusersgroups)r6   r8  ZwarningOnlyZrequestingUserCanEditZeditorsr$   rd   rZ   r   rY   )	rI   r   r6  r7  r8  r9  r:  r   r   rC   rC   rD   add_protected_range  s&    /zWorksheet.add_protected_range)rd   r@   c                 C   s"   ddd|iigi}| j | j|S )zDelete protected range identified by the ID ``id``.

        To retrieve the ID of a protected range use the following method
        to list them all: :func:`~gspread.Spreadsheet.list_protected_ranges`
        r   ZdeleteProtectedRangeZprotectedRangeIdrZ   r   rY   )rI   rd   r   rC   rC   rD   delete_protected_range?  s    
z Worksheet.delete_protected_range)r  r  r  r@   c                 C   s   |du r|}ddd| j ||d |diigi}| j| j|}|du rJ|}|| d }|tjkrx| jd d  |8  < n |tjkr| jd d	  |8  < |S )
a  Deletes multi rows from the worksheet at the specified index.

        :param dimension: A dimension to delete. ``Dimension.rows`` or ``Dimension.cols``.
        :type dimension: :class:`~gspread.utils.Dimension`
        :param int start_index: Index of a first row for deletion.
        :param int end_index: Index of a last row for deletion. When
            ``end_index`` is not specified this method only deletes a single
            row at ``start_index``.
        Nr   ZdeleteDimensionr6   r   r  rm   rn   rp   )rd   rZ   r   rY   r   r   r^   r   )rI   r  r  r  r   r  Znum_deletedrC   rC   rD   delete_dimensionR  s.    

zWorksheet.delete_dimension)r  r  r@   c                 C   s   |  tj||S )a  Deletes multiple rows from the worksheet at the specified index.

        :param int start_index: Index of a first row for deletion.
        :param int end_index: Index of a last row for deletion.
            When end_index is not specified this method only deletes a single
            row at ``start_index``.

        Example::

            # Delete rows 5 to 10 (inclusive)
            worksheet.delete_rows(5, 10)

            # Delete only the second row
            worksheet.delete_rows(2)

        )r@  r   r   rI   r  r  rC   rC   rD   delete_rowsz  s    zWorksheet.delete_rowsc                 C   s   |  tj||S )aK  Deletes multiple columns from the worksheet at the specified index.

        :param int start_index: Index of a first column for deletion.
        :param int end_index: Index of a last column for deletion.
            When end_index is not specified this method only deletes a single
            column at ``start_index``.
        )r@  r   r   rA  rC   rC   rD   delete_columns  s    
zWorksheet.delete_columnsc                 C   s   | j | jt| jS )z"Clears all cells in the worksheet.)rZ   Zvalues_clearrY   r&   rc   rH   rC   rC   rD   clear  s    zWorksheet.clear)r   r@   c                    s0    fdd|D }d|i} j j j|d}|S )a  Clears multiple ranges of cells with 1 API call.

        `Batch Clear`_

        .. _Batch Clear: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchClear

        Examples::

            worksheet.batch_clear(['A1:B1','my_range'])

            # Note: named ranges are defined in the scope of
            # a spreadsheet, so even if `my_range` does not belong to
            # this sheet it is still updated

        .. versionadded:: 3.8.0

        c                    s   g | ]}t  j|qS rC   r   )r   rngrH   rC   rD   r     r   z)Worksheet.batch_clear.<locals>.<listcomp>r   r   )rZ   Zvalues_batch_clearrY   )rI   r   r   r   rC   rH   rD   batch_clear  s    zWorksheet.batch_clear)funcquerycase_sensitivein_row	in_columnr@   c           
         s   | j | jt| j}zt|d }W n ty<   g }Y n0 | |||}t|t	rr|t
td fdd}	n.t|tjr|t
tdfdd}	ntd||	|S )Nr9   )r   r@   c                    s.    s| j d u r| j kS | j   kS d S r   )r   casefoldr~   )rI  	str_queryrC   rD   match  s    
z Worksheet._finder.<locals>.matchc                    s     | jd uS r   )searchr   r~   )re_queryrC   rD   rN    s    zIquery must be of type: 'str' or 're.Pattern' (obtained from re.compile()))rZ   r   rY   r&   rc   r,   r   _list_cellsr]   rR   r   boolrePatternr	  )
rI   rG  rH  rI  rJ  rK  r   r9   cellsrN  rC   )rI  rP  rM  rD   _finder  s$    

zWorksheet._finder)r9   rJ  rK  r@   c                    sr   dur durt d dur6 fddt|D S dur\fddt|d  D S dd t|D S dS )z~Returns a list of ``Cell`` instances scoped by optional
        ``in_row``` or ``in_column`` values (both one-based).
        Nz3Either 'in_row' or 'in_column' should be specified.c              	      s.   g | ]&\}}t |d   t| d   dqS r   r   rR   )r   r   r   )rK  rC   rD   r     s   z)Worksheet._list_cells.<locals>.<listcomp>c                    s&   g | ]\}}t  |d  t|dqS r   rW  )r   r   r   )rJ  rC   rD   r     s   r   c                 S   s<   g | ]4\}}t |D ]"\}}t|d  |d  t|dqqS r   )r   r   rR   r   rC   rC   rD   r     s   )r	  r   )rI   r9   rJ  rK  rC   )rK  rJ  rD   rQ    s    	

zWorksheet._list_cells)rH  rJ  rK  rI  r@   c                 C   s2   zt | t||||W S  ty,   Y dS 0 dS )a  Finds the first cell matching the query.

        :param query: A literal string to match or compiled regular expression.
        :type query: str, :py:class:`re.RegexObject`
        :param int in_row: (optional) One-based row number to scope the search.
        :param int in_column: (optional) One-based column number to scope
            the search.
        :param bool case_sensitive: (optional) comparison is case sensitive if
            set to True, case insensitive otherwise. Default is True.
            Does not apply to regular expressions.
        :returns: the first matching cell or None otherwise
        :rtype: :class:`gspread.cell.Cell`
        N)nextrV  filterStopIterationrI   rH  rJ  rK  rI  rC   rC   rD   find	  s    zWorksheet.findc                 C   s   dd |  t||||D S )a  Finds all cells matching the query.

        Returns a list of :class:`gspread.cell.Cell`.

        :param query: A literal string to match or compiled regular expression.
        :type query: str, :py:class:`re.RegexObject`
        :param int in_row: (optional) One-based row number to scope the search.
        :param int in_column: (optional) One-based column number to scope
            the search.
        :param bool case_sensitive: (optional) comparison is case sensitive if
            set to True, case insensitive otherwise. Default is True.
            Does not apply to regular expressions.
        :returns: the list of all matching cells or empty list otherwise
        :rtype: list
        c                 S   s   g | ]}|qS rC   rC   )r   elemrC   rC   rD   r   1	  s   z%Worksheet.findall.<locals>.<listcomp>)rV  rY  r[  rC   rC   rD   findall	  s    zWorksheet.findallc                 C   s   i }|dur||d< |dur$||d< |s0t dddd | D }dd	| j|d
|digi}| j| j|}|dur|| jd d< |dur|| jd d< |S )zFreeze rows and/or columns on the worksheet.

        :param rows: Number of rows to freeze.
        :param cols: Number of columns to freeze.
        Nrs   ru   r  r   c                 s   s   | ]}d | V  qdS r  rC   r  rC   rC   rD   r   I	  r   z#Worksheet.freeze.<locals>.<genexpr>r   r  r  r  rm   r  r
  rC   rC   rD   freeze6	  s0    zWorksheet.freezec                 C   sD   |durt || jnd| ji}dddd|iiigi}| j| j|S )a*  Add a basic filter to the worksheet. If a range or boundaries
        are passed, the filter will be limited to the given range.

        :param str name: A string with range value in A1 notation,
            e.g. ``A1:A5``.

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        .. versionadded:: 3.4
        Nrf   r   ZsetBasicFilterrY  r6   r<  rI   r   r   r   rC   rC   rD   set_basic_filter`	  s    zWorksheet.set_basic_filterc                 C   s$   ddd| j iigi}| j| j|S )zQRemove the basic filter from a worksheet.

        .. versionadded:: 3.4
        r   ZclearBasicFilterrf   r  )rI   r   rC   rC   rD   clear_basic_filter|	  s    
zWorksheet.clear_basic_filter)rZ   rY   sheet_idrW   insert_sheet_indexnew_sheet_idnew_sheet_namer@   c                 C   sF   dd||||digi}| ||}	|	d d d d }
t||
||S )a	  Class method to duplicate a :class:`gspread.worksheet.Worksheet`.

        :param Session client: The HTTP client used for the HTTP request
        :param str spreadsheet_id: The spreadsheet ID (used for the HTTP request)
        :param int sheet_id: The original sheet ID
        :param int insert_sheet_index: (optional) The zero-based index
            where the new sheet should be inserted. The index of all sheets
            after this are incremented.
        :param int new_sheet_id: (optional) The ID of the new sheet.
            If not set, an ID is chosen. If set, the ID must not conflict with
            any existing sheet ID. If set, it must be non-negative.
        :param str new_sheet_name: (optional) The name of the new sheet.
            If empty, a new name is chosen for you.

        :returns: a newly created :class:`gspread.worksheet.Worksheet`.

        .. note::
           This is a class method in order for the spreadsheet class
           to use it without an instance of a Worksheet object
        r   ZduplicateSheet)ZsourceSheetIdZinsertSheetIndexZ
newSheetIdZnewSheetNameZrepliesr   rX   )r   rV   )r>   rZ   rY   rc  rW   rd  re  rf  r   r   rX   rC   rC   rD   
_duplicate	  s    !zWorksheet._duplicate)rd  re  rf  r@   c              	   C   s    t j| j| j| j| j|||dS )a  Duplicate the sheet.

        :param int insert_sheet_index: (optional) The zero-based index
            where the new sheet should be inserted. The index of all sheets
            after this are incremented.
        :param int new_sheet_id: (optional) The ID of the new sheet.
            If not set, an ID is chosen. If set, the ID must not conflict with
            any existing sheet ID. If set, it must be non-negative.
        :param str new_sheet_name: (optional) The name of the new sheet.
            If empty, a new name is chosen for you.

        :returns: a newly created :class:`gspread.worksheet.Worksheet`.

        .. versionadded:: 3.1
        )rd  re  rf  )rV   rg  rZ   rY   rd   rW   )rI   rd  re  rf  rC   rC   rD   	duplicate	  s    zWorksheet.duplicate)destination_spreadsheet_idr@   c                 C   s   | j | j| j|S )a  Copies this sheet to another spreadsheet.

        :param str spreadsheet_id: The ID of the spreadsheet to copy
            the sheet to.
        :returns: a dict with the response containing information about
            the newly created sheet.
        :rtype: dict
        )rZ   Zspreadsheets_sheets_copy_torY   rd   )rI   ri  rC   rC   rD   copy_to	  s    
zWorksheet.copy_to)r   
merge_typer@   c                 C   s0   t || j}dd||digi}| j| j|S )ad  Merge cells.

        :param str name: Range name in A1 notation, e.g. 'A1:A5'.
        :param merge_type: (optional) one of ``MergeType.merge_all``,
            ``MergeType.merge_columns``, or ``MergeType.merge_rows``. Defaults to ``MergeType.merge_all``.
            See `MergeType`_ in the Sheets API reference.
        :type merge_type: :namedtuple:`~gspread.utils.MergeType`

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        :returns: the response body from the request
        :rtype: dict

        .. _MergeType: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#MergeType

        r   Z
mergeCells)Z	mergeTyper6   r<  )rI   r   rk  r   r   rC   rC   rD   merge_cells	  s    zWorksheet.merge_cellsc                 C   s.   t || j}ddd|iigi}| j| j|S )a  Unmerge cells.

        Unmerge previously merged cells.

        :param str name: Range name in A1 notation, e.g. 'A1:A5'.

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        :returns: the response body from the request
        :rtype: dict
        r   ZunmergeCellsr6   r<  r`  rC   rC   rD   unmerge_cells
  s    
zWorksheet.unmerge_cells)default_empty_valuer@   c                 C   s|   ddi}| j | j|}|d | j d d di g}g }|D ]6}|g  |dg D ]}|d |d	| qZq@|S )
at  Returns a list of lists containing all notes in the sheet.

        .. note::

            The resulting matrix is not necessarily square.
            The matrix is as tall as the last row with a note,
            and each row is only as long as the last column in that row with a note.


            Please see the example below.
            To ensure it is square, use `gspread.utils.fill_gaps`,
            for example like `utils.fill_gaps(arr, len(arr), max(len(a) for a in arr), None)`

        :param str default_empty_value: (optional) Determines which value to use
            for cells without notes, defaults to None.

        Examples::

            # Note data:
            #      A      B
            # 1    A1     -
            # 2    -      B2

            # Read all notes from the sheet
            >>> arr = worksheet.get_notes()
            >>> print(arr)
            [
                ["A1"],
                ["", "B2"]
            ]
            >>> print(gspread.utils.fill_gaps(arr, len(arr), max(len(a) for a in arr), None))
            [
                ["A1", ""],
                ["", "B2"]
            ]
        r   zsheets.data.rowData.values.noter   r   r   rowDatar9   r   note)rZ   spreadsheets_getrY   ri   rB   r   )rI   rn  r   r  r   notesr   r   rC   rC   rD   	get_notes1
  s    % 
zWorksheet.get_notes)r   r@   c              	   C   sr   t | j|}|dd}| j| j|}z,|d d d d d d d d d }W n ttfyl   d	}Y n0 |S )
zGet the content of the note located at `cell`, or the empty string if the
        cell does not have a note.

        :param str cell: A string with cell coordinates in A1 notation,
            e.g. 'D7'.
        zsheets/data/rowData/values/note)r   r   r   r   r   ro  r9   rp  r[   )r&   rc   rZ   rq  rY   rL   r   )rI   r   Zabsolute_cellr   r  rp  rC   rC   rD   get_notea
  s    ,
zWorksheet.get_note)rr  r@   c                 C   sz   dg i}|  D ]T\}}t|ts2td||dt|| jddd|igigdi}|d | q| j	| j
| dS )a  update multiple notes. The notes are attached to a certain cell.

        :param notes dict: A dict of notes with their cells coordinates and respective content

            dict format is:

            * key: the cell coordinates as A1 range format
            * value: the string content of the cell

            Example::

                {
                    "D7": "Please read my notes",
                    "GH42": "this one is too far",
                }

        .. versionadded:: 5.9
        r   z4Only string allowed as content for a note: '{} - {}'ZupdateCellsrp  r9   )r6   r   r   N)itemsr]   rR   r	  r7   r$   rd   r   rZ   r   rY   )rI   rr  r   r6   contentreqrC   rC   rD   update_notesv
  s*    

zWorksheet.update_notes)r   rv  r@   c                 C   s   |  ||i dS )zUpdate the content of the note located at `cell`.

        :param str cell: A string with cell coordinates in A1 notation,
            e.g. 'D7'.
        :param str note: The text note to insert.

        .. versionadded:: 3.7
        Nrx  rI   r   rv  rC   rC   rD   update_note
  s    
zWorksheet.update_notec                 C   s   |  ||i dS )a  Insert a note. The note is attached to a certain cell.

        :param str cell: A string with cell coordinates in A1 notation,
            e.g. 'D7'.
        :param str content: The text note to insert.

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        .. versionadded:: 3.7
        Nry  rz  rC   rC   rD   insert_note
  s    zWorksheet.insert_notec                 C   s   |  | dS )a  insert multiple notes. The notes are attached to a certain cell.

        :param notes dict: A dict of notes with their cells coordinates and respective content

            dict format is:

            * key: the cell coordinates as A1 range format
            * value: the string content of the cell

            Example::

                {
                    "D7": "Please read my notes",
                    "GH42": "this one is too far",
                }

        .. versionadded:: 5.9
        Nry  )rI   rr  rC   rC   rD   insert_notes
  s    zWorksheet.insert_notesc                 C   s   dd |D }|  | dS )zClear all notes located at the at the coordinates
        pointed to by ``ranges``.

        :param ranges list: List of A1 coordinates where to clear the notes.
            e.g. ``["A1", "GH42", "D7"]``
        c                 S   s   i | ]
}|d qS )r[   rC   r   rC   rC   rD   
<dictcomp>
  r   z)Worksheet.clear_notes.<locals>.<dictcomp>Nry  )rI   r   rr  rC   rC   rD   clear_notes
  s    zWorksheet.clear_notesc                 C   s   |  |di dS )a  Clear a note. The note is attached to a certain cell.

        :param str cell: A string with cell coordinates in A1 notation,
            e.g. 'D7'.

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        .. versionadded:: 3.7
        r[   Nry  )rI   r   rC   rC   rD   
clear_note
  s    zWorksheet.clear_note)r   r   r@   c                 C   s0   ddd|t || jdiigi}| j| j|S )a  
        :param str name: A string with range value in A1 notation,
            e.g. 'A1:A5'.

        Alternatively, you may specify numeric boundaries. All values
        index from 1 (one):

        :param int first_row: First row number
        :param int first_col: First column number
        :param int last_row: Last row number
        :param int last_col: Last column number

        :param range_name: The name to assign to the range of cells

        :returns: the response body from the request
        :rtype: dict
        r   ZaddNamedRangeZ
namedRange)r   r6   r<  )rI   r   r   r   rC   rC   rD   define_named_range
  s    
zWorksheet.define_named_range)named_range_idr@   c                 C   s"   ddd|iigi}| j | j|S )z
        :param str named_range_id: The ID of the named range to delete.
            Can be obtained with Spreadsheet.list_named_ranges()

        :returns: the response body from the request
        :rtype: dict
        r   ZdeleteNamedRangeZnamedRangeIdr>  )rI   r  r   rC   rC   rD   delete_named_range  s    		zWorksheet.delete_named_range)r   r   r  r@   c                 C   s.   ddd| j |||diigi}| j| j|S )aT  
        update this sheet by grouping 'dimension'

        :param int start: The start (inclusive) of the group
        :param int end: The end (exclusive) of the grou
        :param str dimension: The dimension to group, can be one of
            ``ROWS`` or ``COLUMNS``.
        :type diension: :class:`~gspread.utils.Dimension`
        r   ZaddDimensionGroupr6   r  r  rI   r   r   r  r   rC   rC   rD   _add_dimension_group0  s    zWorksheet._add_dimension_group)r   r   r@   c                 C   s   |  ||tjS )a  
        Group columns in order to hide them in the UI.

        .. note::

            API behavior with nested groups and non-matching ``[start:end)``
            range can be found here: `Add Dimension Group Request`_

            .. _Add Dimension Group Request: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddDimensionGroupRequest

        :param int start: The start (inclusive) of the group
        :param int end: The end (exclusive) of the group
        )r  r   r   rI   r   r   rC   rC   rD   add_dimension_group_columnsM  s    z%Worksheet.add_dimension_group_columnsc                 C   s   |  ||tjS )aX  
        Group rows in order to hide them in the UI.

        .. note::

            API behavior with nested groups and non-matching ``[start:end)``
            range can be found here `Add Dimension Group Request`_

        :param int start: The start (inclusive) of the group
        :param int end: The end (exclusive) of the group
        )r  r   r   r  rC   rC   rD   add_dimension_group_rows]  s    z"Worksheet.add_dimension_group_rowsc                 C   s.   ddd| j |||diigi}| j| j|S )z&delete a dimension group in this sheetr   ZdeleteDimensionGroupr6   r  r  r  rC   rC   rD   _delete_dimension_groupk  s    z!Worksheet._delete_dimension_groupc                 C   s   |  ||tjS )a  
        Remove the grouping of a set of columns.

        .. note::

            API behavior with nested groups and non-matching ``[start:end)``
            range can be found here `Delete Dimension Group Request`_

            .. _Delete Dimension Group Request: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#DeleteDimensionGroupRequest

        :param int start: The start (inclusive) of the group
        :param int end: The end (exclusive) of the group
        )r  r   r   r  rC   rC   rD   delete_dimension_group_columns  s    z(Worksheet.delete_dimension_group_columnsc                 C   s   |  ||tjS )aT  
        Remove the grouping of a set of rows.

        .. note::
            API behavior with nested groups and non-matching ``[start:end)``
            range can be found here `Delete Dimension Group Request`_

        :param int start: The start (inclusive) of the group
        :param int end: The end (exclusive) of the group
        )r  r   r   r  rC   rC   rD   delete_dimension_group_rows  s    z%Worksheet.delete_dimension_group_rowsc                 C   s   |  dg S )z
        List all the grouped columns in this worksheet.

        :returns: list of the grouped columns
        :rtype: list
        ZcolumnGroupsr   rH   rC   rC   rD   list_dimension_group_columns  s    z&Worksheet.list_dimension_group_columnsc                 C   s   |  dg S )z
        List all the grouped rows in this worksheet.

        :returns: list of the grouped rows
        :rtype: list
        Z	rowGroupsr  rH   rC   rC   rD   list_dimension_group_rows  s    z#Worksheet.list_dimension_group_rowsc                 C   s6   dd| j |||dddiddigi}| j| j|S )a  
        Update this sheet by hiding the given 'dimension'

        Index starts from 0.

        :param int start: The (inclusive) start of the dimension to hide
        :param int end: The (exclusive) end of the dimension to hide
        :param str dimension: The dimension to hide, can be one of
            ``ROWS`` or ``COLUMNS``.
        :type diension: :class:`~gspread.utils.Dimension`
        r   updateDimensionPropertiesr  hiddenByUserTr6   rX   r   r  r  rC   rC   rD   _hide_dimension  s    zWorksheet._hide_dimensionc                 C   s   |  ||tjS )z
        Explicitly hide the given column index range.

        Index starts from 0.

        :param int start: The (inclusive) starting column to hide
        :param int end: The (exclusive) end column to hide
        )r  r   r   r  rC   rC   rD   hide_columns  s    	zWorksheet.hide_columnsc                 C   s   |  ||tjS )z
        Explicitly hide the given row index range.

        Index starts from 0.

        :param int start: The (inclusive) starting row to hide
        :param int end: The (exclusive) end row to hide
        )r  r   r   r  rC   rC   rD   	hide_rows  s    	zWorksheet.hide_rowsc                 C   s6   dd| j |||dddiddigi}| j| j|S )a  
        Update this sheet by unhiding the given 'dimension'

        Index starts from 0.

        :param int start: The (inclusive) start of the dimension to unhide
        :param int end: The (inclusive) end of the dimension to unhide
        :param str dimension: The dimension to hide, can be one of
            ``ROWS`` or ``COLUMNS``.
        :type dimension: :class:`~gspread.utils.Dimension`
        r   r  r  r  Fr  r  r  rC   rC   rD   _unhide_dimension  s    zWorksheet._unhide_dimensionc                 C   s   |  ||tjS )z
        Explicitly unhide the given column index range.

        Index start from 0.

        :param int start: The (inclusive) starting column to hide
        :param int end: The (exclusive) end column to hide
        )r  r   r   r  rC   rC   rD   unhide_columns  s    	zWorksheet.unhide_columnsc                 C   s   |  ||tjS )z
        Explicitly unhide the given row index range.

        Index start from 0.

        :param int start: The (inclusive) starting row to hide
        :param int end: The (exclusive) end row to hide
        )r  r   r   r  rC   rC   rD   unhide_rows  s    	zWorksheet.unhide_rows)rj   r@   c                 C   s:   dd| j |dddigi}| j| j|}|| jd< |S )z?Send the appropriate request to hide/show the current worksheetr   r  )rf   rj   rj   r  r  rI   rj   r   r  rC   rC   rD   _set_hidden_flag!  s    
zWorksheet._set_hidden_flagc                 C   s
   |  dS )z(Hides the current worksheet from the UI.Tr  rH   rC   rC   rD   hide6  s    zWorksheet.hidec                 C   s
   |  dS )z%Show the current worksheet in the UI.Fr  rH   rC   rC   rD   show:  s    zWorksheet.showc                 C   sB   dd| j d|idddigi}| j| j|}|| jd d< |S )z,Hide/show gridlines on the current worksheetr   r  rw   r  zgridProperties.hideGridlinesr  rm   r  r  rC   rC   rD   _set_gridlines_hidden_flag>  s    z$Worksheet._set_gridlines_hidden_flagc                 C   s
   |  dS )z'Hide gridlines on the current worksheetTr  rH   rC   rC   rD   hide_gridlinesU  s    zWorksheet.hide_gridlinesc                 C   s
   |  dS )z'Show gridlines on the current worksheetFr  rH   rC   rC   rD   show_gridlinesY  s    zWorksheet.show_gridlines)sourcedest
paste_typepaste_orientationr@   c                 C   s8   ddt || jt || j||digi}| j| j|S )a>  Copies a range of data from source to dest

        .. note::

           ``paste_type`` values are explained here: `Paste Types`_

           .. _Paste Types: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#pastetype

        :param str source: The A1 notation of the source range to copy
        :param str dest: The A1 notation of the destination where to paste the data
            Can be the A1 notation of the top left corner where the range must be paste
            ex: G16, or a complete range notation ex: G16:I20.
            The dimensions of the destination range is not checked and has no effect,
            if the destination range does not match the source range dimension, the entire
            source range is copies anyway.
        :param paste_type: the paste type to apply. Many paste type are available from
            the Sheet API, see above note for detailed values for all values and their effects.
            Defaults to ``PasteType.normal``
        :type paste_type: :class:`~gspread.utils.PasteType`
        :param paste_orientation: The paste orient to apply.
            Possible values are: ``normal`` to keep the same orientation, ``transpose`` where all rows become columns and vice versa.
        :type paste_orientation: :class:`~gspread.utils.PasteOrientation`
        r   Z	copyPaste)r  destination	pasteTypeZpasteOrientationr<  )rI   r  r  r  r  r   rC   rC   rD   
copy_range]  s    

zWorksheet.copy_range)r  r  r  r@   c                 C   sN   t || j}ddt || j|d |d |d d|digi}| j| j|S )a  Moves a range of data form source to dest

        .. note::

           ``paste_type`` values are explained here: `Paste Types`_

           .. _Paste Types: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#pastetype

        :param str source: The A1 notation of the source range to move
        :param str dest: The A1 notation of the destination where to paste the data
            **it must be a single cell** in the A1 notation. ex: G16
        :param paste_type: the paste type to apply. Many paste type are available from
            the Sheet API, see above note for detailed values for all values and their effects.
            Defaults to ``PasteType.normal``
        :type paste_type: :class:`~gspread.utils.PasteType`
        r   ZcutPasterf   r   r   )rf   ZrowIndexZcolumnIndex)r  r  r  r<  )rI   r  r  r  Z	grid_destr   rC   rC   rD   	cut_range  s    
zWorksheet.cut_range)r6   condition_typer9   inputMessagestrictshowCustomUir@   c           	      C   s\   t |tstdt|| j}dd||dd |D d|||ddigi}| j| j|S )	a7  Adds a data validation rule to any given range.

        .. note::

            ``condition_type`` values are explained here: `ConditionType`_

            .. _ConditionType: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#ConditionType


        :param str source: The A1 notation of the source range to move
        :param condition_type: The sort of condition to apply.
        :param values: List of condition values.
        :type values: Any
        :param str inputMessage: Message to show for the validation.
        :param bool strict: Whether to reject invalid data or not.
        :param bool showCustomUi: Whether to show a custom UI(Dropdown) for list values.

        **Examples**

        .. code-block:: python

            import gspread
            from gspread.utils import ValidationConditionType


            ...

            ws = spreadsheet.sheet1

            ws.add_validation(
                'A1',
                ValidationConditionType.number_greater,
                [10],
                strict=True,
                inputMessage='Value must be greater than 10',
            )

            ws.add_validation(
                'C2:C7',
                ValidationConditionType.one_of_list,
                ['Yes','No'],
                showCustomUi=True
            )
        z?condition_type param should be a valid ValidationConditionType.r   ZsetDataValidationc                 S   s   g | ]}d |iqS )ZuserEnteredValuerC   )r   r   rC   rC   rD   r     s   z,Worksheet.add_validation.<locals>.<listcomp>)typer9   )	conditionr  r  r  )r6   rule)r]   r!   r	  r$   rd   rZ   r   rY   )	rI   r6   r  r9   r  r  r  gridr   rC   rC   rD   add_validation  s,    6
zWorksheet.add_validation)NN)r[   )NNN)NNN)NTNNNNN)TNNNN)NN)N)N)N)NN)NN)NNT)NNT)NN)N)NNN)NNN)r[   )NFF)rN   rO   rP   rQ   r   rR   r   r   r   r`   re   rU   intrd   rW   rc   rh   ri   rR  rl   ro   rq   rr   rt   rv   rx   rz   ry   r    r   r#   	formattedr   r   r   r'   r   r6   r   r   r   r   r   r;   r   r   r   r   floatr   r   r   r   JSONResponser   r   r"   r   r
   r   rB   r   r   r   r4   r   r7   r  r   r	   r  r  r  r  r  r   r#  r%  r&  r'  r   r   r+  r*  r0  r/  r5  r=  r?  r@  rB  rC  rD  rF  r   r   rS  rT  rV  rQ  r\  r^  r_  ra  rb  rT   rg  rh  rj  r   Z	merge_allrl  rm  rs  rt  rx  r{  r|  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   normalr   r  r  r!   r  rC   rC   rC   rD   rV      s   
&
.J
s  O%
; I  X      
     uD2+F!	*2*KAI
)  ,      *  4  !! 03
 	
##13  rV   )CrQ   rS  r   typingr   r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   
exceptionsr   http_clientr   r   urlsr   utilsr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   rW   r3   rR   r4   r8   r  r:   r   r;   rV   rC   rC   rC   rD   <module>   s*   Lp

	L