import six
import re


def GetKeyName(key, quote=True, omit_indices=False):
  """Returns the string representation for a parsed key.

  This is the inverse of Lexer.Key(). That docstring has the input/output
  details for this function.

  Args:
    key: A parsed key, which is an ordered list of key names/indices. Each
      element in the list may be one of:
        str - A resource property name. This could be a class attribute name or
          a dict index.
        int - A list index. Selects one member is the list. Negative indices
          count from the end of the list, starting with -1 for the last element
          in the list. An out of bounds index is not an error; it produces the
          value None.
        None - A list slice. Selects all members of a list or dict like object.
          A slice of an empty dict or list is an empty dict or list.
    quote: "..." the key name if it contains non-alphanum characters.
    omit_indices: Omit [...] indices if True.

  Returns:
    The string representation of the parsed key.
  """
  parts = []
  for part in key:
    if part is None:
      if omit_indices:
        continue
      part = '[]'
      if parts:
        parts[-1] += part
        continue
    elif isinstance(part, six.integer_types):
      if omit_indices:
        continue
      part = '[{part}]'.format(part=part)
      if parts:
        parts[-1] += part
        continue
    elif quote and re.search(r'[^-@\w]', part):
      part = part.replace('\\', '\\\\')
      part = part.replace('"', '\\"')
      part = '"{part}"'.format(part=part)
    parts.append(part)
  return '.'.join(parts) if parts else '.'