import json
import six


def _HandleJsonList(response, service, method, errors):
  """Extracts data from one *List response page as JSON and stores in dicts.

  Args:
    response: str, The *List response in JSON
    service: The service which responded to *List request
    method: str, Method used to list resources. One of 'List' or
      'AggregatedList'.
    errors: list, Errors from response will be appended to  this list.

  Returns:
    Pair of:
    - List of items returned in response as dicts
    - Next page token (if present, otherwise None).
  """
  items = []

  response = json.loads(response)

  # If the request is a list call, then yield the items directly.
  if method == 'List':
    items = response.get('items', [])

  # If the request is an aggregatedList call, then do all the
  # magic necessary to get the actual resources because the
  # aggregatedList responses are very complicated data
  # structures...
  elif method == 'AggregatedList':
    items_field_name = service.GetMethodConfig(
        'AggregatedList').relative_path.split('/')[-1]
    for scope_result in six.itervalues(response['items']):
      # If the given scope is unreachable, record the warning
      # message in the errors list.
      warning = scope_result.get('warning', None)
      if warning and warning['code'] == 'UNREACHABLE':
        errors.append((None, warning['message']))

      items.extend(scope_result.get(items_field_name, []))

  return items, response.get('nextPageToken', None)