#!/usr/bin/env python
"""CLI for dns, version v1."""
# NOTE: This file is autogenerated and should not be edited by hand.

import code
import os
import platform
import sys

from apitools.base.protorpclite import message_types
from apitools.base.protorpclite import messages

from google.apputils import appcommands
import gflags as flags

import apitools.base.py as apitools_base
from apitools.base.py import cli as apitools_base_cli
import dns_v1_client as client_lib
import dns_v1_messages as messages


def _DeclareDnsFlags():
  """Declare global flags in an idempotent way."""
  if 'api_endpoint' in flags.FLAGS:
    return
  flags.DEFINE_string(
      'api_endpoint',
      u'https://www.googleapis.com/dns/v1/',
      'URL of the API endpoint to use.',
      short_name='dns_url')
  flags.DEFINE_string(
      'history_file',
      u'~/.dns.v1.history',
      'File with interactive shell history.')
  flags.DEFINE_multistring(
      'add_header', [],
      'Additional http headers (as key=value strings). '
      'Can be specified multiple times.')
  flags.DEFINE_string(
      'service_account_json_keyfile', '',
      'Filename for a JSON service account key downloaded'
      ' from the Developer Console.')
  flags.DEFINE_enum(
      'alt',
      u'json',
      [u'json'],
      u'Data format for the response.')
  flags.DEFINE_string(
      'fields',
      None,
      u'Selector specifying which fields to include in a partial response.')
  flags.DEFINE_string(
      'key',
      None,
      u'API key. Your API key identifies your project and provides you with '
      u'API access, quota, and reports. Required unless you provide an OAuth '
      u'2.0 token.')
  flags.DEFINE_string(
      'oauth_token',
      None,
      u'OAuth 2.0 token for the current user.')
  flags.DEFINE_boolean(
      'prettyPrint',
      'True',
      u'Returns response with indentations and line breaks.')
  flags.DEFINE_string(
      'quotaUser',
      None,
      u'Available to use for quota purposes for server-side applications. Can'
      u' be any arbitrary string assigned to a user, but should not exceed 40'
      u' characters. Overrides userIp if both are provided.')
  flags.DEFINE_string(
      'trace',
      None,
      'A tracing token of the form "token:<tokenid>" to include in api '
      'requests.')
  flags.DEFINE_string(
      'userIp',
      None,
      u'IP address of the site where the request originates. Use this if you '
      u'want to enforce per-user limits.')


FLAGS = flags.FLAGS
apitools_base_cli.DeclareBaseFlags()
_DeclareDnsFlags()


def GetGlobalParamsFromFlags():
  """Return a StandardQueryParameters based on flags."""
  result = messages.StandardQueryParameters()
  if FLAGS['alt'].present:
    result.alt = messages.StandardQueryParameters.AltValueValuesEnum(FLAGS.alt)
  if FLAGS['fields'].present:
    result.fields = FLAGS.fields.decode('utf8')
  if FLAGS['key'].present:
    result.key = FLAGS.key.decode('utf8')
  if FLAGS['oauth_token'].present:
    result.oauth_token = FLAGS.oauth_token.decode('utf8')
  if FLAGS['prettyPrint'].present:
    result.prettyPrint = FLAGS.prettyPrint
  if FLAGS['quotaUser'].present:
    result.quotaUser = FLAGS.quotaUser.decode('utf8')
  if FLAGS['trace'].present:
    result.trace = FLAGS.trace.decode('utf8')
  if FLAGS['userIp'].present:
    result.userIp = FLAGS.userIp.decode('utf8')
  return result


def GetClientFromFlags():
  """Return a client object, configured from flags."""
  log_request = FLAGS.log_request or FLAGS.log_request_response
  log_response = FLAGS.log_response or FLAGS.log_request_response
  api_endpoint = apitools_base.NormalizeApiEndpoint(FLAGS.api_endpoint)
  additional_http_headers = dict(x.split('=', 1) for x in FLAGS.add_header)
  credentials_args = {
      'service_account_json_keyfile': os.path.expanduser(FLAGS.service_account_json_keyfile)
  }
  try:
    client = client_lib.DnsV1(
        api_endpoint, log_request=log_request,
        log_response=log_response,
        credentials_args=credentials_args,
        additional_http_headers=additional_http_headers)
  except apitools_base.CredentialsError as e:
    print 'Error creating credentials: %s' % e
    sys.exit(1)
  return client


class PyShell(appcommands.Cmd):

  def Run(self, _):
    """Run an interactive python shell with the client."""
    client = GetClientFromFlags()
    params = GetGlobalParamsFromFlags()
    for field in params.all_fields():
      value = params.get_assigned_value(field.name)
      if value != field.default:
        client.AddGlobalParam(field.name, value)
    banner = """
           == dns interactive console ==
                 client: a dns client
          apitools_base: base apitools module
         messages: the generated messages module
    """
    local_vars = {
        'apitools_base': apitools_base,
        'client': client,
        'client_lib': client_lib,
        'messages': messages,
    }
    if platform.system() == 'Linux':
      console = apitools_base_cli.ConsoleWithReadline(
          local_vars, histfile=FLAGS.history_file)
    else:
      console = code.InteractiveConsole(local_vars)
    try:
      console.interact(banner)
    except SystemExit as e:
      return e.code


class ChangesCreate(apitools_base_cli.NewCmd):
  """Command wrapping changes.Create."""

  usage = """changes_create <project> <managedZone>"""

  def __init__(self, name, fv):
    super(ChangesCreate, self).__init__(name, fv)
    flags.DEFINE_string(
        'change',
        None,
        u'A Change resource to be passed as the request body.',
        flag_values=fv)

  def RunWithArgs(self, project, managedZone):
    """Atomically update the ResourceRecordSet collection.

    Args:
      project: Identifies the project addressed by this request.
      managedZone: Identifies the managed zone addressed by this request. Can
        be the managed zone name or id.

    Flags:
      change: A Change resource to be passed as the request body.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsChangesCreateRequest(
        project=project.decode('utf8'),
        managedZone=managedZone.decode('utf8'),
        )
    if FLAGS['change'].present:
      request.change = apitools_base.JsonToMessage(messages.Change, FLAGS.change)
    result = client.changes.Create(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ChangesGet(apitools_base_cli.NewCmd):
  """Command wrapping changes.Get."""

  usage = """changes_get <project> <managedZone> <changeId>"""

  def __init__(self, name, fv):
    super(ChangesGet, self).__init__(name, fv)

  def RunWithArgs(self, project, managedZone, changeId):
    """Fetch the representation of an existing Change.

    Args:
      project: Identifies the project addressed by this request.
      managedZone: Identifies the managed zone addressed by this request. Can
        be the managed zone name or id.
      changeId: The identifier of the requested change, from a previous
        ResourceRecordSetsChangeResponse.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsChangesGetRequest(
        project=project.decode('utf8'),
        managedZone=managedZone.decode('utf8'),
        changeId=changeId.decode('utf8'),
        )
    result = client.changes.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ChangesList(apitools_base_cli.NewCmd):
  """Command wrapping changes.List."""

  usage = """changes_list <project> <managedZone>"""

  def __init__(self, name, fv):
    super(ChangesList, self).__init__(name, fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Optional. Maximum number of results to be returned. If unspecified,'
        u' the server will decide how many results to return.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        u'Optional. A tag returned by a previous list request that was '
        u'truncated. Use this parameter to continue a previous list request.',
        flag_values=fv)
    flags.DEFINE_enum(
        'sortBy',
        u'changeSequence',
        [u'changeSequence'],
        u'Sorting criterion. The only supported value is change sequence.',
        flag_values=fv)
    flags.DEFINE_string(
        'sortOrder',
        None,
        u"Sorting order direction: 'ascending' or 'descending'.",
        flag_values=fv)

  def RunWithArgs(self, project, managedZone):
    """Enumerate Changes to a ResourceRecordSet collection.

    Args:
      project: Identifies the project addressed by this request.
      managedZone: Identifies the managed zone addressed by this request. Can
        be the managed zone name or id.

    Flags:
      maxResults: Optional. Maximum number of results to be returned. If
        unspecified, the server will decide how many results to return.
      pageToken: Optional. A tag returned by a previous list request that was
        truncated. Use this parameter to continue a previous list request.
      sortBy: Sorting criterion. The only supported value is change sequence.
      sortOrder: Sorting order direction: 'ascending' or 'descending'.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsChangesListRequest(
        project=project.decode('utf8'),
        managedZone=managedZone.decode('utf8'),
        )
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    if FLAGS['sortBy'].present:
      request.sortBy = messages.DnsChangesListRequest.SortByValueValuesEnum(FLAGS.sortBy)
    if FLAGS['sortOrder'].present:
      request.sortOrder = FLAGS.sortOrder.decode('utf8')
    result = client.changes.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ManagedZonesCreate(apitools_base_cli.NewCmd):
  """Command wrapping managedZones.Create."""

  usage = """managedZones_create <project>"""

  def __init__(self, name, fv):
    super(ManagedZonesCreate, self).__init__(name, fv)
    flags.DEFINE_string(
        'managedZone',
        None,
        u'A ManagedZone resource to be passed as the request body.',
        flag_values=fv)

  def RunWithArgs(self, project):
    """Create a new ManagedZone.

    Args:
      project: Identifies the project addressed by this request.

    Flags:
      managedZone: A ManagedZone resource to be passed as the request body.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsManagedZonesCreateRequest(
        project=project.decode('utf8'),
        )
    if FLAGS['managedZone'].present:
      request.managedZone = apitools_base.JsonToMessage(messages.ManagedZone, FLAGS.managedZone)
    result = client.managedZones.Create(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ManagedZonesDelete(apitools_base_cli.NewCmd):
  """Command wrapping managedZones.Delete."""

  usage = """managedZones_delete <project> <managedZone>"""

  def __init__(self, name, fv):
    super(ManagedZonesDelete, self).__init__(name, fv)

  def RunWithArgs(self, project, managedZone):
    """Delete a previously created ManagedZone.

    Args:
      project: Identifies the project addressed by this request.
      managedZone: Identifies the managed zone addressed by this request. Can
        be the managed zone name or id.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsManagedZonesDeleteRequest(
        project=project.decode('utf8'),
        managedZone=managedZone.decode('utf8'),
        )
    result = client.managedZones.Delete(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ManagedZonesGet(apitools_base_cli.NewCmd):
  """Command wrapping managedZones.Get."""

  usage = """managedZones_get <project> <managedZone>"""

  def __init__(self, name, fv):
    super(ManagedZonesGet, self).__init__(name, fv)

  def RunWithArgs(self, project, managedZone):
    """Fetch the representation of an existing ManagedZone.

    Args:
      project: Identifies the project addressed by this request.
      managedZone: Identifies the managed zone addressed by this request. Can
        be the managed zone name or id.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsManagedZonesGetRequest(
        project=project.decode('utf8'),
        managedZone=managedZone.decode('utf8'),
        )
    result = client.managedZones.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ManagedZonesList(apitools_base_cli.NewCmd):
  """Command wrapping managedZones.List."""

  usage = """managedZones_list <project>"""

  def __init__(self, name, fv):
    super(ManagedZonesList, self).__init__(name, fv)
    flags.DEFINE_string(
        'dnsName',
        None,
        u'Restricts the list to return only zones with this domain name.',
        flag_values=fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Optional. Maximum number of results to be returned. If unspecified,'
        u' the server will decide how many results to return.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        u'Optional. A tag returned by a previous list request that was '
        u'truncated. Use this parameter to continue a previous list request.',
        flag_values=fv)

  def RunWithArgs(self, project):
    """Enumerate ManagedZones that have been created but not yet deleted.

    Args:
      project: Identifies the project addressed by this request.

    Flags:
      dnsName: Restricts the list to return only zones with this domain name.
      maxResults: Optional. Maximum number of results to be returned. If
        unspecified, the server will decide how many results to return.
      pageToken: Optional. A tag returned by a previous list request that was
        truncated. Use this parameter to continue a previous list request.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsManagedZonesListRequest(
        project=project.decode('utf8'),
        )
    if FLAGS['dnsName'].present:
      request.dnsName = FLAGS.dnsName.decode('utf8')
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    result = client.managedZones.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ProjectsGet(apitools_base_cli.NewCmd):
  """Command wrapping projects.Get."""

  usage = """projects_get <project>"""

  def __init__(self, name, fv):
    super(ProjectsGet, self).__init__(name, fv)

  def RunWithArgs(self, project):
    """Fetch the representation of an existing Project.

    Args:
      project: Identifies the project addressed by this request.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsProjectsGetRequest(
        project=project.decode('utf8'),
        )
    result = client.projects.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ResourceRecordSetsList(apitools_base_cli.NewCmd):
  """Command wrapping resourceRecordSets.List."""

  usage = """resourceRecordSets_list <project> <managedZone>"""

  def __init__(self, name, fv):
    super(ResourceRecordSetsList, self).__init__(name, fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Optional. Maximum number of results to be returned. If unspecified,'
        u' the server will decide how many results to return.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Restricts the list to return only records with this fully qualified'
        u' domain name.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        u'Optional. A tag returned by a previous list request that was '
        u'truncated. Use this parameter to continue a previous list request.',
        flag_values=fv)
    flags.DEFINE_string(
        'type',
        None,
        u'Restricts the list to return only records of this type. If present,'
        u' the "name" parameter must also be present.',
        flag_values=fv)

  def RunWithArgs(self, project, managedZone):
    """Enumerate ResourceRecordSets that have been created but not yet
    deleted.

    Args:
      project: Identifies the project addressed by this request.
      managedZone: Identifies the managed zone addressed by this request. Can
        be the managed zone name or id.

    Flags:
      maxResults: Optional. Maximum number of results to be returned. If
        unspecified, the server will decide how many results to return.
      name: Restricts the list to return only records with this fully
        qualified domain name.
      pageToken: Optional. A tag returned by a previous list request that was
        truncated. Use this parameter to continue a previous list request.
      type: Restricts the list to return only records of this type. If
        present, the "name" parameter must also be present.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.DnsResourceRecordSetsListRequest(
        project=project.decode('utf8'),
        managedZone=managedZone.decode('utf8'),
        )
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    if FLAGS['type'].present:
      request.type = FLAGS.type.decode('utf8')
    result = client.resourceRecordSets.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


def main(_):
  appcommands.AddCmd('pyshell', PyShell)
  appcommands.AddCmd('changes_create', ChangesCreate)
  appcommands.AddCmd('changes_get', ChangesGet)
  appcommands.AddCmd('changes_list', ChangesList)
  appcommands.AddCmd('managedZones_create', ManagedZonesCreate)
  appcommands.AddCmd('managedZones_delete', ManagedZonesDelete)
  appcommands.AddCmd('managedZones_get', ManagedZonesGet)
  appcommands.AddCmd('managedZones_list', ManagedZonesList)
  appcommands.AddCmd('projects_get', ProjectsGet)
  appcommands.AddCmd('resourceRecordSets_list', ResourceRecordSetsList)

  apitools_base_cli.SetupLogger()
  if hasattr(appcommands, 'SetDefaultCommand'):
    appcommands.SetDefaultCommand('pyshell')


run_main = apitools_base_cli.run_main

if __name__ == '__main__':
  appcommands.Run()
