
    #                         d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlmZ ddl	m
Z dd	l	mZ d
Z G d dej                        Zy)z4Custom table printer for CAI team's asset query API.    )absolute_import)division)print_function)unicode_literalsN)extra_types)custom_printer_base)resource_printer
cloudassetc                   8    e Zd ZdZed        Zd Zd Zd Zd Z	y)AssetQueryPrinterzBPrints the asset query response in a custom human readable format.c                     t        j                  t        t        d       | j                  j                  t               y)z3Register this custom printer with the given parser.T)hiddenN)r	   RegisterFormatterASSET_QUERY_PRINTER_FORMATr   display_info	AddFormat)parsers    ;lib/googlecloudsdk/command_lib/asset/asset_query_printer.pyRegisterzAssetQueryPrinter.Register#   s0     &&"$5dD
!!"<=    c                    t         j                  j                  |      }d|v r"d|d   v r|d   d= d|d   v r|d   d= |d   s|d= t        j                         }t        j                  |d|       |j                         S )NqueryResultrowsschemayamlout)r   encodingMessageToPyValueioStringIOr	   Printgetvalue)selfrespresp_message
string_bufs       r   _FormatMetadataz!AssetQueryPrinter._FormatMetadata*   s    ''88>L$	<.	.'/	\-0	0'1-('J<Z@  r   c                    t        |d      rt        |j                  d      sy|j                  j                  }|j                  j                  }g }|j                  syt        j                         }|j                  dj                  dj                  d |j                  D                           |D ]b  }t        j                  j                  |      }t        j                  j                  |      }|j                  | j                  ||d             d t        j                         }	t        j                   ||j#                         |	       t%        j&                  |	j#                         g      S )	u  Formats rows in a [QueryAssetsResponse]'s queryResults into a table.

    Args:
      resp: The [QueryAssetsResponse] that contains 0 or more rows.

    Returns:
      A 'Lines' custom printer object that corresponds to the formatted table
      when printed out.

    The response.queryResult.rows in response:
    {
      "jobReference":
      "CiBqb2JfdDR2SFgwa3BPNFpQVDFudVJJaW5TdVNfS1N0YxIBAxjH8ZmAo6qckik",
      "done": true,
      "queryResult": {
        "rows": [
          {
            "f": [
              {
                "v":
                "//cloudresourcemanager.googleapis.com/folders/417243649856"
              }
            ]
          }
        ],
        "schema": {
          "fields": [
            {
              "field": "name",
              "type": "STRING",
              "mode": "NULLABLE"
            }
          ]
        },
        "total_rows": 1
      }
    }
    Will return a custom printer Lines object holding the following string:
    ┌────────────────────────────────────────────────────────────┐
    │                            name                            │
    ├────────────────────────────────────────────────────────────┤
    │ //cloudresourcemanager.googleapis.com/folders/417243649856 │
    └────────────────────────────────────────────────────────────┘
    r   r   Nztable[box]({})z, c              3   h   K   | ]*  }d j                  |j                  |j                         , yw)z{}:label={}N)formatfield).0r,   s     r   	<genexpr>z4AssetQueryPrinter._FormatRowTable.<locals>.<genexpr>x   s-      6$"E 	U[[%++6"s   02Fr   )hasattrr   r   r   fieldsr    r!   writer+   joinr   r   r   append_ConvertFromFVr	   r"   r#   cpLines)
r$   r%   r   r   row_list	schemabufrowrow_jsonschema_jsonraw_outs
             r   _FormatRowTablez!AssetQueryPrinter._FormatRowTable:   s3   b 4'wt7G7G7?0A$$F  DH ==IOO$++DII 6$]]6$ -$ % &  %%66s;h((99&Akood))+xGH  kkmG8Y%7%7%9wG 88W%%'())r   c                    |sy|j                  dg       D cg c]  }|j                  dd       }}i }|}|s|d   }t        ||      D ]  \  }}	d|vrt        d      |d   j                         dk(  r|j                  dg       }
|j                  dd	      j                         d
k(  r8|	D cg c]%  }| j	                  |
|j                  dd      d      ' c}||d   <   | j	                  |
|	d      }|r	|||d   <   d||d   <   |j                  dd	      j                         d
k(  r-|	D cg c]  }|j                  dd       }}||nd||d   <   |	r|	nd||d   <    |S c c}w c c}w c c}w )aH  Converts from FV format to values.

    Args:
      schema: The schema struct within the queryResult struct in the response.
      row: A single row of the response's queryResult.rows message.
      is_record: True if the row object is a record within an actual row.

    Returns:
      A dictionary mapping row keys to the values that may be a simple datatype,
      a record (struct) in the form of a dictionary, or a list of either simple
      data types or records (again, in the form of dictionaries).

    Raises:
      IOError: An error occurred accessing the smalltable.
     fvr0   typez'Invalid response: missing type propertyRECORDmodeNULLABLEREPEATEDTr,   )getzipIOErrorupperr4   )r$   r   r9   	is_recordentryvaluesresult
new_schemar,   rA   	subfieldssubvaluecur_vals                r   r4   z AssetQueryPrinter._ConvertFromFV   s     .1ggc2.>?.>UeiiR .>F?FJ(#j
F+q	u	?@@	v			(	*IIh+	99VZ(..0J>  $( !!)X\\#r-BDI$&w
  ''	1d;'%,F5>"%'F5>"99VZ(..0J>9:;X8<<R(;,3,?RuW~ '(RuW~3 ,4 MA @$ <s   E+/*E01E5c                     t        |d      st        |d      sy| j                  |      }| j                  |      }g }|r|j                  |       |r|j                  |       t	        j
                  |d      S )zBTransforms a CAI [QueryAssetsResponse] into human-readable format.jobReferenceerrorN<   )max_column_width)r/   r(   r=   r3   r5   Section)r$   r%   metadatar   sections_lists        r   	TransformzAssetQueryPrinter.Transform   sr     4(w1G##D)H%DM8$4 ::mb99r   N)
__name__
__module____qualname____doc__staticmethodr   r(   r=   r4   r[    r   r   r   r       s.    J> >! L*\3j:r   r   )r_   
__future__r   r   r   r   r    apitools.base.pyr   googlecloudsdk.core.resourcer   r5   r	   r   CustomPrinterBaser   ra   r   r   <module>rf      s>    ; &  % ' 	 ( B 9 * k:,, k:r   