
    !                         d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlmZ ddlm	Z	 ddlm
Z
 dd	lmZ dd
lmZ ddlmZ dZdZdZdZd Zd Zd Zd Zd Zd Zd ZddZ	 	 	 	 	 	 	 	 ddZy)a4  Generalized Apigee Management API request handler.

The Apigee Management APIs were designed before One Platform, and include some
design decisions incompatible with apitools (see b/151099218). So the gcloud
apigee surface must make its own HTTPS requests instead of relying on an
apitools-generated client.
    )absolute_import)division)unicode_literalsN)defaults)errors)resource_args)
properties)requests)urllibzapigee.googleapis.comz%s-apigee.googleapis.comerrormessagec                     t        j                         }|D ]T  }t        j                  |   }|j                  dz   }|| vs| |   t        j                  |j                        | |   ||<   V |S )aL  Returns an OrderedDict uniquely identifying the resource to be accessed.

  Args:
    identifiers: a collection that maps entity type names to identifiers.
    entity_path: a list of entity type names from least to most specific.

  Raises:
    MissingIdentifierError: an entry in entity_path is missing from
      `identifiers`.
  Id)collectionsOrderedDictr   ENTITIESpluralr   MissingIdentifierErrorsingular)identifiersentity_pathresource_identifierentity_nameentityid_keys         0lib/googlecloudsdk/command_lib/apigee/request.py_ResourceIdentifierr   ,   sz     $//1 k##K0F]]T!F[ K$7$?))&//::"-f"5 ! 
    c                     t        j                         j                  || ||d      }|j                  }|j                  }|j
                  }|||fS )zHReturns HTTP status, reason, and response body for a given HTTP request.T)dataheadersstream)r
   
GetSessionrequeststatus_codereasoncontent)urlmethodbodyr!   responsestatusr&   r    s           r   _Communicater-   B   sW      "**cgd + <(&??&			$		r   c                 ^    t        | t              st        | d      r| j                         } | S )zReturns decoded string.

  Args:
    response: the raw string or bytes of JSON data

  Raises:
    ValueError: failure to load/decode JSON data
  decode)
isinstancestrhasattrr/   )r+   s    r   _DecodeResponser3   L   s(     
Hc	"wx'B H	/r   c                     | xs |d   S )z)Gets resource type from the inputed data. )entity_collectionr   s     r   _GetResourceTyper8   \   s    		-k"o-r   c                     t        j                  | j                         D cg c]  \  }}|j                  |f c}}      S c c}}w )z*Builds error identifier from inputed data.)r   r   itemsr   )r   keyvalues      r   _BuildErrorIdentifierr=   a   sH    		 	 .A.G.G.I".I
Us||U.I" 
  "s   A
c                     t        j                  |       }t        |v r6t        |t           t              rt
        |t           v r|t           t
           S y)zHExtracts error message from response, returns None if message not found.N)jsonloadsERROR_FIELDr0   dictMESSAGE_FIELD)r+   json_responses     r   _ExtractErrorMessagerE   h   sJ    **X&-M!jK 
'{!;;%m44	r   c                 B    t        j                  |       }t        |      S )z2Returns the Apigee host based on the organization.)r   GetOrganizationLocation_GetApigeeHostByLocation)organizationlocations     r   _GetApigeeHostByOrganizationrK   r   s    --l;(	!(	++r   c                 2    | | dk(  s| st         S t        | z  S )z.Returns the Apigee host based on the location.global)APIGEE_GLOBAL_HOSTAPIGEE_LEP_HOST)rJ   s    r   rH   rH   x   s"    X-X	8	##r   c
                    i }
|r||
d<   |r||
d<   t        | |      }dg}|j                         D ]3  \  }}||j                  t        j                  j                  |      gz  }5 |rKt        j                  |   j                  }|j                  t        j                  j                  |             |rt        j                  j                  |      nd}t        j                  j                  j                  j                         }|	rd}t        |	      }nY|r8t        j                  j!                  |      }|j"                  }|j$                  }nd}| j'                  dd      }t)        |      }dj+                  |      }|r|d	   d
k(  r||z  }d}|r|}t        j                  j-                  |||d|df      }t/        ||||
      \  }}}|dk\  rut1        ||      }|dk(  rt2        j4                  }n%|dv rt2        j6                  }nt2        j8                  }t;        |      }	 t=        t?        |            } |||||||      |#	 t?        |      }tC        jD                  |      }|S |S # t@        $ r d}Y Bw xY w# t@        $ r4}t1        ||      }t;        |      }t3        jF                  ||||      d}~ww xY w)a  Makes a request to the Apigee API and returns the response.

  Args:
    identifiers: a collection that maps entity type names to identifiers.
    entity_path: a list of entity type names from least to most specific.
    entity_collection: if provided, the final entity type; the request will not
      be specific as to which entity of that type is being referenced.
    method: an HTTP method string specifying what to do with the accessed
      entity. If the method begins with a colon, it will be interpreted as a
      Cloud custom method (https://cloud.google.com/apis/design/custom_methods)
      and appended to the request URL with the POST HTTP method.
    query_params: any extra query parameters to be sent in the request.
    accept_mimetype: the mimetype to expect in the response body. If not
      provided, the response will be parsed as JSON.
    body: data to send in the request body.
    body_mimetype: the mimetype of the body data, if not JSON.
    method_override: the HTTP method to use for the request, when method starts
      with a colon.
    location: the location of the apigee organization.

  Returns:
    an object containing the API's response. If accept_mimetype was set, this
      will be raw bytes. Otherwise, it will be a parsed JSON object.

  Raises:
    MissingIdentifierError: an entry in entity_path is missing from
      `identifiers`.
    RequestError: if the request itself fails.
  zContent-TypeAcceptv1 httpsorganizationsIdN/r   :POSTi  i  )i  i  )	user_help)$r   r:   r   r   parsequoter   r   append	urlencoder	   VALUESapi_endpoint_overridesapigeeGetrH   urlparseschemenetlocgetrK   join
urlunparser-   r8   r   EntityNotFoundErrorUnauthorizedRequestErrorRequestErrorr=   rE   r3   
ValueErrorr?   r@   ResponseNotJSONError) r   r   r7   r)   query_paramsaccept_mimetyper*   body_mimetypemethod_overriderJ   r!   r   url_path_elementsr;   r<   collection_namequery_stringendpoint_overriderc   hostendpointrI   url_pathr(   r,   r&   r+   resource_typeexception_classerror_identifierrY   r   s                                    r   ResponseToApiRequestr{      s   N '	+GN'GH+KEf'--/jc5#**fll&8&8&?@@ 0#,,->?FFOV\\//@A9E''52, ''>>EEIIKF#H-D||$$%67H__F??DF??#4d;L'5DXX'((q	S HFfx\2 NO#)#vtWE&&(s]$%6DM}22o	:	77o++o,-@A&x'@Ai -)96 (iA A 2 *hH%h 
//!  i  2&'8+Fm./BC''}>N(02 22s*   &I/  J  /I=<I= 	J=	/J88J=)N)NGETNNNzapplication/jsonNN)__doc__
__future__r   r   r   r   r?   !googlecloudsdk.command_lib.apigeer   r   r   googlecloudsdk.corer	   googlecloudsdk.core.credentialsr
   	six.movesr   rN   rO   rA   rC   r   r-   r3   r8   r=   rE   rK   rH   r{   r6   r   r   <module>r      s    '  '   6 4 ; * 4  - ,, .
,$ ,0 %&*)-"'9)-"&lr   