#!/usr/bin/env python
"""CLI for fusiontables, 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 fusiontables_v1_client as client_lib
import fusiontables_v1_messages as messages


def _DeclareFusiontablesFlags():
  """Declare global flags in an idempotent way."""
  if 'api_endpoint' in flags.FLAGS:
    return
  flags.DEFINE_string(
      'api_endpoint',
      u'https://www.googleapis.com/fusiontables/v1/',
      'URL of the API endpoint to use.',
      short_name='fusiontables_url')
  flags.DEFINE_string(
      'history_file',
      u'~/.fusiontables.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'csv', 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()
_DeclareFusiontablesFlags()


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.FusiontablesV1(
        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 = """
           == fusiontables interactive console ==
                 client: a fusiontables 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 ColumnDelete(apitools_base_cli.NewCmd):
  """Command wrapping column.Delete."""

  usage = """column_delete <tableId> <columnId>"""

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

  def RunWithArgs(self, tableId, columnId):
    """Deletes the column.

    Args:
      tableId: Table from which the column is being deleted.
      columnId: Name or identifier for the column being deleted.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesColumnDeleteRequest(
        tableId=tableId.decode('utf8'),
        columnId=columnId.decode('utf8'),
        )
    result = client.column.Delete(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ColumnGet(apitools_base_cli.NewCmd):
  """Command wrapping column.Get."""

  usage = """column_get <tableId> <columnId>"""

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

  def RunWithArgs(self, tableId, columnId):
    """Retrieves a specific column by its id.

    Args:
      tableId: Table to which the column belongs.
      columnId: Name or identifier for the column that is being requested.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesColumnGetRequest(
        tableId=tableId.decode('utf8'),
        columnId=columnId.decode('utf8'),
        )
    result = client.column.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ColumnInsert(apitools_base_cli.NewCmd):
  """Command wrapping column.Insert."""

  usage = """column_insert <tableId>"""

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

  def RunWithArgs(self, tableId):
    """Adds a new column to the table.

    Args:
      tableId: Table for which a new column is being added.

    Flags:
      column: A Column resource to be passed as the request body.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesColumnInsertRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['column'].present:
      request.column = apitools_base.JsonToMessage(messages.Column, FLAGS.column)
    result = client.column.Insert(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ColumnList(apitools_base_cli.NewCmd):
  """Command wrapping column.List."""

  usage = """column_list <tableId>"""

  def __init__(self, name, fv):
    super(ColumnList, self).__init__(name, fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Maximum number of columns to return. Optional. Default is 5.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        u'Continuation token specifying which result page to return. '
        u'Optional.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Retrieves a list of columns.

    Args:
      tableId: Table whose columns are being listed.

    Flags:
      maxResults: Maximum number of columns to return. Optional. Default is 5.
      pageToken: Continuation token specifying which result page to return.
        Optional.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesColumnListRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    result = client.column.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ColumnPatch(apitools_base_cli.NewCmd):
  """Command wrapping column.Patch."""

  usage = """column_patch <tableId> <columnId>"""

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

  def RunWithArgs(self, tableId, columnId):
    """Updates the name or type of an existing column. This method supports
    patch semantics.

    Args:
      tableId: Table for which the column is being updated.
      columnId: Name or identifier for the column that is being updated.

    Flags:
      column: A Column resource to be passed as the request body.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesColumnPatchRequest(
        tableId=tableId.decode('utf8'),
        columnId=columnId.decode('utf8'),
        )
    if FLAGS['column'].present:
      request.column = apitools_base.JsonToMessage(messages.Column, FLAGS.column)
    result = client.column.Patch(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class ColumnUpdate(apitools_base_cli.NewCmd):
  """Command wrapping column.Update."""

  usage = """column_update <tableId> <columnId>"""

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

  def RunWithArgs(self, tableId, columnId):
    """Updates the name or type of an existing column.

    Args:
      tableId: Table for which the column is being updated.
      columnId: Name or identifier for the column that is being updated.

    Flags:
      column: A Column resource to be passed as the request body.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesColumnUpdateRequest(
        tableId=tableId.decode('utf8'),
        columnId=columnId.decode('utf8'),
        )
    if FLAGS['column'].present:
      request.column = apitools_base.JsonToMessage(messages.Column, FLAGS.column)
    result = client.column.Update(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class QuerySql(apitools_base_cli.NewCmd):
  """Command wrapping query.Sql."""

  usage = """query_sql <sql>"""

  def __init__(self, name, fv):
    super(QuerySql, self).__init__(name, fv)
    flags.DEFINE_boolean(
        'hdrs',
        None,
        u'Should column names be included (in the first row)?. Default is '
        u'true.',
        flag_values=fv)
    flags.DEFINE_boolean(
        'typed',
        None,
        u'Should typed values be returned in the (JSON) response -- numbers '
        u'for numeric values and parsed geometries for KML values? Default is'
        u' true.',
        flag_values=fv)
    flags.DEFINE_string(
        'download_filename',
        '',
        'Filename to use for download.',
        flag_values=fv)
    flags.DEFINE_boolean(
        'overwrite',
        'False',
        'If True, overwrite the existing file when downloading.',
        flag_values=fv)

  def RunWithArgs(self, sql):
    """Executes an SQL SELECT/INSERT/UPDATE/DELETE/SHOW/DESCRIBE/CREATE
    statement.

    Args:
      sql: An SQL SELECT/SHOW/DESCRIBE/INSERT/UPDATE/DELETE/CREATE statement.

    Flags:
      hdrs: Should column names be included (in the first row)?. Default is
        true.
      typed: Should typed values be returned in the (JSON) response -- numbers
        for numeric values and parsed geometries for KML values? Default is
        true.
      download_filename: Filename to use for download.
      overwrite: If True, overwrite the existing file when downloading.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesQuerySqlRequest(
        sql=sql.decode('utf8'),
        )
    if FLAGS['hdrs'].present:
      request.hdrs = FLAGS.hdrs
    if FLAGS['typed'].present:
      request.typed = FLAGS.typed
    download = None
    if FLAGS.download_filename:
      download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite,
          progress_callback=apitools_base.DownloadProgressPrinter,
          finish_callback=apitools_base.DownloadCompletePrinter)
    result = client.query.Sql(
        request, global_params=global_params, download=download)
    print apitools_base_cli.FormatOutput(result)


class QuerySqlGet(apitools_base_cli.NewCmd):
  """Command wrapping query.SqlGet."""

  usage = """query_sqlGet <sql>"""

  def __init__(self, name, fv):
    super(QuerySqlGet, self).__init__(name, fv)
    flags.DEFINE_boolean(
        'hdrs',
        None,
        u'Should column names be included (in the first row)?. Default is '
        u'true.',
        flag_values=fv)
    flags.DEFINE_boolean(
        'typed',
        None,
        u'Should typed values be returned in the (JSON) response -- numbers '
        u'for numeric values and parsed geometries for KML values? Default is'
        u' true.',
        flag_values=fv)
    flags.DEFINE_string(
        'download_filename',
        '',
        'Filename to use for download.',
        flag_values=fv)
    flags.DEFINE_boolean(
        'overwrite',
        'False',
        'If True, overwrite the existing file when downloading.',
        flag_values=fv)

  def RunWithArgs(self, sql):
    """Executes an SQL SELECT/SHOW/DESCRIBE statement.

    Args:
      sql: An SQL SELECT/SHOW/DESCRIBE statement.

    Flags:
      hdrs: Should column names be included (in the first row)?. Default is
        true.
      typed: Should typed values be returned in the (JSON) response -- numbers
        for numeric values and parsed geometries for KML values? Default is
        true.
      download_filename: Filename to use for download.
      overwrite: If True, overwrite the existing file when downloading.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesQuerySqlGetRequest(
        sql=sql.decode('utf8'),
        )
    if FLAGS['hdrs'].present:
      request.hdrs = FLAGS.hdrs
    if FLAGS['typed'].present:
      request.typed = FLAGS.typed
    download = None
    if FLAGS.download_filename:
      download = apitools_base.Download.FromFile(FLAGS.download_filename, overwrite=FLAGS.overwrite,
          progress_callback=apitools_base.DownloadProgressPrinter,
          finish_callback=apitools_base.DownloadCompletePrinter)
    result = client.query.SqlGet(
        request, global_params=global_params, download=download)
    print apitools_base_cli.FormatOutput(result)


class StyleDelete(apitools_base_cli.NewCmd):
  """Command wrapping style.Delete."""

  usage = """style_delete <tableId> <styleId>"""

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

  def RunWithArgs(self, tableId, styleId):
    """Deletes a style.

    Args:
      tableId: Table from which the style is being deleted
      styleId: Identifier (within a table) for the style being deleted
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesStyleDeleteRequest(
        tableId=tableId.decode('utf8'),
        styleId=styleId,
        )
    result = client.style.Delete(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class StyleGet(apitools_base_cli.NewCmd):
  """Command wrapping style.Get."""

  usage = """style_get <tableId> <styleId>"""

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

  def RunWithArgs(self, tableId, styleId):
    """Gets a specific style.

    Args:
      tableId: Table to which the requested style belongs
      styleId: Identifier (integer) for a specific style in a table
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesStyleGetRequest(
        tableId=tableId.decode('utf8'),
        styleId=styleId,
        )
    result = client.style.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class StyleInsert(apitools_base_cli.NewCmd):
  """Command wrapping style.Insert."""

  usage = """style_insert <tableId>"""

  def __init__(self, name, fv):
    super(StyleInsert, self).__init__(name, fv)
    flags.DEFINE_string(
        'kind',
        u'fusiontables#styleSetting',
        u'Type name: an individual style setting. A StyleSetting contains the'
        u' style defintions for points, lines, and polygons in a table. Since'
        u' a table can have any one or all of them, a style definition can '
        u'have point, line and polygon style definitions.',
        flag_values=fv)
    flags.DEFINE_string(
        'markerOptions',
        None,
        u'Style definition for points in the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Optional name for the style setting.',
        flag_values=fv)
    flags.DEFINE_string(
        'polygonOptions',
        None,
        u'Style definition for polygons in the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'polylineOptions',
        None,
        u'Style definition for lines in the table.',
        flag_values=fv)
    flags.DEFINE_integer(
        'styleId',
        None,
        u'Identifier for the style setting (unique only within tables).',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Adds a new style for the table.

    Args:
      tableId: Identifier for the table.

    Flags:
      kind: Type name: an individual style setting. A StyleSetting contains
        the style defintions for points, lines, and polygons in a table. Since
        a table can have any one or all of them, a style definition can have
        point, line and polygon style definitions.
      markerOptions: Style definition for points in the table.
      name: Optional name for the style setting.
      polygonOptions: Style definition for polygons in the table.
      polylineOptions: Style definition for lines in the table.
      styleId: Identifier for the style setting (unique only within tables).
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.StyleSetting(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['kind'].present:
      request.kind = FLAGS.kind.decode('utf8')
    if FLAGS['markerOptions'].present:
      request.markerOptions = apitools_base.JsonToMessage(messages.PointStyle, FLAGS.markerOptions)
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    if FLAGS['polygonOptions'].present:
      request.polygonOptions = apitools_base.JsonToMessage(messages.PolygonStyle, FLAGS.polygonOptions)
    if FLAGS['polylineOptions'].present:
      request.polylineOptions = apitools_base.JsonToMessage(messages.LineStyle, FLAGS.polylineOptions)
    if FLAGS['styleId'].present:
      request.styleId = FLAGS.styleId
    result = client.style.Insert(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class StyleList(apitools_base_cli.NewCmd):
  """Command wrapping style.List."""

  usage = """style_list <tableId>"""

  def __init__(self, name, fv):
    super(StyleList, self).__init__(name, fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Maximum number of styles to return. Optional. Default is 5.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        u'Continuation token specifying which result page to return. '
        u'Optional.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Retrieves a list of styles.

    Args:
      tableId: Table whose styles are being listed

    Flags:
      maxResults: Maximum number of styles to return. Optional. Default is 5.
      pageToken: Continuation token specifying which result page to return.
        Optional.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesStyleListRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    result = client.style.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class StylePatch(apitools_base_cli.NewCmd):
  """Command wrapping style.Patch."""

  usage = """style_patch <tableId> <styleId>"""

  def __init__(self, name, fv):
    super(StylePatch, self).__init__(name, fv)
    flags.DEFINE_string(
        'kind',
        u'fusiontables#styleSetting',
        u'Type name: an individual style setting. A StyleSetting contains the'
        u' style defintions for points, lines, and polygons in a table. Since'
        u' a table can have any one or all of them, a style definition can '
        u'have point, line and polygon style definitions.',
        flag_values=fv)
    flags.DEFINE_string(
        'markerOptions',
        None,
        u'Style definition for points in the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Optional name for the style setting.',
        flag_values=fv)
    flags.DEFINE_string(
        'polygonOptions',
        None,
        u'Style definition for polygons in the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'polylineOptions',
        None,
        u'Style definition for lines in the table.',
        flag_values=fv)

  def RunWithArgs(self, tableId, styleId):
    """Updates an existing style. This method supports patch semantics.

    Args:
      tableId: Identifier for the table.
      styleId: Identifier for the style setting (unique only within tables).

    Flags:
      kind: Type name: an individual style setting. A StyleSetting contains
        the style defintions for points, lines, and polygons in a table. Since
        a table can have any one or all of them, a style definition can have
        point, line and polygon style definitions.
      markerOptions: Style definition for points in the table.
      name: Optional name for the style setting.
      polygonOptions: Style definition for polygons in the table.
      polylineOptions: Style definition for lines in the table.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.StyleSetting(
        tableId=tableId.decode('utf8'),
        styleId=styleId,
        )
    if FLAGS['kind'].present:
      request.kind = FLAGS.kind.decode('utf8')
    if FLAGS['markerOptions'].present:
      request.markerOptions = apitools_base.JsonToMessage(messages.PointStyle, FLAGS.markerOptions)
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    if FLAGS['polygonOptions'].present:
      request.polygonOptions = apitools_base.JsonToMessage(messages.PolygonStyle, FLAGS.polygonOptions)
    if FLAGS['polylineOptions'].present:
      request.polylineOptions = apitools_base.JsonToMessage(messages.LineStyle, FLAGS.polylineOptions)
    result = client.style.Patch(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class StyleUpdate(apitools_base_cli.NewCmd):
  """Command wrapping style.Update."""

  usage = """style_update <tableId> <styleId>"""

  def __init__(self, name, fv):
    super(StyleUpdate, self).__init__(name, fv)
    flags.DEFINE_string(
        'kind',
        u'fusiontables#styleSetting',
        u'Type name: an individual style setting. A StyleSetting contains the'
        u' style defintions for points, lines, and polygons in a table. Since'
        u' a table can have any one or all of them, a style definition can '
        u'have point, line and polygon style definitions.',
        flag_values=fv)
    flags.DEFINE_string(
        'markerOptions',
        None,
        u'Style definition for points in the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Optional name for the style setting.',
        flag_values=fv)
    flags.DEFINE_string(
        'polygonOptions',
        None,
        u'Style definition for polygons in the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'polylineOptions',
        None,
        u'Style definition for lines in the table.',
        flag_values=fv)

  def RunWithArgs(self, tableId, styleId):
    """Updates an existing style.

    Args:
      tableId: Identifier for the table.
      styleId: Identifier for the style setting (unique only within tables).

    Flags:
      kind: Type name: an individual style setting. A StyleSetting contains
        the style defintions for points, lines, and polygons in a table. Since
        a table can have any one or all of them, a style definition can have
        point, line and polygon style definitions.
      markerOptions: Style definition for points in the table.
      name: Optional name for the style setting.
      polygonOptions: Style definition for polygons in the table.
      polylineOptions: Style definition for lines in the table.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.StyleSetting(
        tableId=tableId.decode('utf8'),
        styleId=styleId,
        )
    if FLAGS['kind'].present:
      request.kind = FLAGS.kind.decode('utf8')
    if FLAGS['markerOptions'].present:
      request.markerOptions = apitools_base.JsonToMessage(messages.PointStyle, FLAGS.markerOptions)
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    if FLAGS['polygonOptions'].present:
      request.polygonOptions = apitools_base.JsonToMessage(messages.PolygonStyle, FLAGS.polygonOptions)
    if FLAGS['polylineOptions'].present:
      request.polylineOptions = apitools_base.JsonToMessage(messages.LineStyle, FLAGS.polylineOptions)
    result = client.style.Update(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TableCopy(apitools_base_cli.NewCmd):
  """Command wrapping table.Copy."""

  usage = """table_copy <tableId>"""

  def __init__(self, name, fv):
    super(TableCopy, self).__init__(name, fv)
    flags.DEFINE_boolean(
        'copyPresentation',
        None,
        u'Whether to also copy tabs, styles, and templates. Default is false.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Copies a table.

    Args:
      tableId: ID of the table that is being copied.

    Flags:
      copyPresentation: Whether to also copy tabs, styles, and templates.
        Default is false.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTableCopyRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['copyPresentation'].present:
      request.copyPresentation = FLAGS.copyPresentation
    result = client.table.Copy(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TableDelete(apitools_base_cli.NewCmd):
  """Command wrapping table.Delete."""

  usage = """table_delete <tableId>"""

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

  def RunWithArgs(self, tableId):
    """Deletes a table.

    Args:
      tableId: ID of the table that is being deleted.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTableDeleteRequest(
        tableId=tableId.decode('utf8'),
        )
    result = client.table.Delete(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TableGet(apitools_base_cli.NewCmd):
  """Command wrapping table.Get."""

  usage = """table_get <tableId>"""

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

  def RunWithArgs(self, tableId):
    """Retrieves a specific table by its id.

    Args:
      tableId: Identifier(ID) for the table being requested.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTableGetRequest(
        tableId=tableId.decode('utf8'),
        )
    result = client.table.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TableImportRows(apitools_base_cli.NewCmd):
  """Command wrapping table.ImportRows."""

  usage = """table_importRows <tableId>"""

  def __init__(self, name, fv):
    super(TableImportRows, self).__init__(name, fv)
    flags.DEFINE_string(
        'delimiter',
        None,
        u'The delimiter used to separate cell values. This can only consist '
        u"of a single character. Default is ','.",
        flag_values=fv)
    flags.DEFINE_string(
        'encoding',
        None,
        u"The encoding of the content. Default is UTF-8. Use 'auto-detect' if"
        u' you are unsure of the encoding.',
        flag_values=fv)
    flags.DEFINE_integer(
        'endLine',
        None,
        u'The index of the last line from which to start importing, '
        u'exclusive. Thus, the number of imported lines is endLine - '
        u'startLine. If this parameter is not provided, the file will be '
        u'imported until the last line of the file. If endLine is negative, '
        u'then the imported content will exclude the last endLine lines. That'
        u' is, if endline is negative, no line will be imported whose index '
        u'is greater than N + endLine where N is the number of lines in the '
        u'file, and the number of imported lines will be N + endLine - '
        u'startLine.',
        flag_values=fv)
    flags.DEFINE_boolean(
        'isStrict',
        None,
        u'Whether the CSV must have the same number of values for each row. '
        u'If false, rows with fewer values will be padded with empty values. '
        u'Default is true.',
        flag_values=fv)
    flags.DEFINE_integer(
        'startLine',
        None,
        u'The index of the first line from which to start importing, '
        u'inclusive. Default is 0.',
        flag_values=fv)
    flags.DEFINE_string(
        'upload_filename',
        '',
        'Filename to use for upload.',
        flag_values=fv)
    flags.DEFINE_string(
        'upload_mime_type',
        '',
        'MIME type to use for the upload. Only needed if the extension on '
        '--upload_filename does not determine the correct (or any) MIME '
        'type.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Import more rows into a table.

    Args:
      tableId: The table into which new rows are being imported.

    Flags:
      delimiter: The delimiter used to separate cell values. This can only
        consist of a single character. Default is ','.
      encoding: The encoding of the content. Default is UTF-8. Use 'auto-
        detect' if you are unsure of the encoding.
      endLine: The index of the last line from which to start importing,
        exclusive. Thus, the number of imported lines is endLine - startLine.
        If this parameter is not provided, the file will be imported until the
        last line of the file. If endLine is negative, then the imported
        content will exclude the last endLine lines. That is, if endline is
        negative, no line will be imported whose index is greater than N +
        endLine where N is the number of lines in the file, and the number of
        imported lines will be N + endLine - startLine.
      isStrict: Whether the CSV must have the same number of values for each
        row. If false, rows with fewer values will be padded with empty
        values. Default is true.
      startLine: The index of the first line from which to start importing,
        inclusive. Default is 0.
      upload_filename: Filename to use for upload.
      upload_mime_type: MIME type to use for the upload. Only needed if the
        extension on --upload_filename does not determine the correct (or any)
        MIME type.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTableImportRowsRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['delimiter'].present:
      request.delimiter = FLAGS.delimiter.decode('utf8')
    if FLAGS['encoding'].present:
      request.encoding = FLAGS.encoding.decode('utf8')
    if FLAGS['endLine'].present:
      request.endLine = FLAGS.endLine
    if FLAGS['isStrict'].present:
      request.isStrict = FLAGS.isStrict
    if FLAGS['startLine'].present:
      request.startLine = FLAGS.startLine
    upload = None
    if FLAGS.upload_filename:
      upload = apitools_base.Upload.FromFile(
          FLAGS.upload_filename, FLAGS.upload_mime_type,
          progress_callback=apitools_base.UploadProgressPrinter,
          finish_callback=apitools_base.UploadCompletePrinter)
    result = client.table.ImportRows(
        request, global_params=global_params, upload=upload)
    print apitools_base_cli.FormatOutput(result)


class TableImportTable(apitools_base_cli.NewCmd):
  """Command wrapping table.ImportTable."""

  usage = """table_importTable <name>"""

  def __init__(self, name, fv):
    super(TableImportTable, self).__init__(name, fv)
    flags.DEFINE_string(
        'delimiter',
        None,
        u'The delimiter used to separate cell values. This can only consist '
        u"of a single character. Default is ','.",
        flag_values=fv)
    flags.DEFINE_string(
        'encoding',
        None,
        u"The encoding of the content. Default is UTF-8. Use 'auto-detect' if"
        u' you are unsure of the encoding.',
        flag_values=fv)
    flags.DEFINE_string(
        'upload_filename',
        '',
        'Filename to use for upload.',
        flag_values=fv)
    flags.DEFINE_string(
        'upload_mime_type',
        '',
        'MIME type to use for the upload. Only needed if the extension on '
        '--upload_filename does not determine the correct (or any) MIME '
        'type.',
        flag_values=fv)

  def RunWithArgs(self, name):
    """Import a new table.

    Args:
      name: The name to be assigned to the new table.

    Flags:
      delimiter: The delimiter used to separate cell values. This can only
        consist of a single character. Default is ','.
      encoding: The encoding of the content. Default is UTF-8. Use 'auto-
        detect' if you are unsure of the encoding.
      upload_filename: Filename to use for upload.
      upload_mime_type: MIME type to use for the upload. Only needed if the
        extension on --upload_filename does not determine the correct (or any)
        MIME type.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTableImportTableRequest(
        name=name.decode('utf8'),
        )
    if FLAGS['delimiter'].present:
      request.delimiter = FLAGS.delimiter.decode('utf8')
    if FLAGS['encoding'].present:
      request.encoding = FLAGS.encoding.decode('utf8')
    upload = None
    if FLAGS.upload_filename:
      upload = apitools_base.Upload.FromFile(
          FLAGS.upload_filename, FLAGS.upload_mime_type,
          progress_callback=apitools_base.UploadProgressPrinter,
          finish_callback=apitools_base.UploadCompletePrinter)
    result = client.table.ImportTable(
        request, global_params=global_params, upload=upload)
    print apitools_base_cli.FormatOutput(result)


class TableInsert(apitools_base_cli.NewCmd):
  """Command wrapping table.Insert."""

  usage = """table_insert"""

  def __init__(self, name, fv):
    super(TableInsert, self).__init__(name, fv)
    flags.DEFINE_string(
        'attribution',
        None,
        u'Optional attribution assigned to the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'attributionLink',
        None,
        u'Optional link for attribution.',
        flag_values=fv)
    flags.DEFINE_string(
        'baseTableIds',
        None,
        u'Optional base table identifier if this table is a view or merged '
        u'table.',
        flag_values=fv)
    flags.DEFINE_string(
        'columns',
        None,
        u'Columns in the table.',
        flag_values=fv)
    flags.DEFINE_string(
        'description',
        None,
        u'Optional description assigned to the table.',
        flag_values=fv)
    flags.DEFINE_boolean(
        'isExportable',
        None,
        u'Variable for whether table is exportable.',
        flag_values=fv)
    flags.DEFINE_string(
        'kind',
        u'fusiontables#table',
        u'Type name: a template for an individual table.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Name assigned to a table.',
        flag_values=fv)
    flags.DEFINE_string(
        'sql',
        None,
        u'Optional sql that encodes the table definition for derived tables.',
        flag_values=fv)
    flags.DEFINE_string(
        'tableId',
        None,
        u'Encrypted unique alphanumeric identifier for the table.',
        flag_values=fv)

  def RunWithArgs(self):
    """Creates a new table.

    Flags:
      attribution: Optional attribution assigned to the table.
      attributionLink: Optional link for attribution.
      baseTableIds: Optional base table identifier if this table is a view or
        merged table.
      columns: Columns in the table.
      description: Optional description assigned to the table.
      isExportable: Variable for whether table is exportable.
      kind: Type name: a template for an individual table.
      name: Name assigned to a table.
      sql: Optional sql that encodes the table definition for derived tables.
      tableId: Encrypted unique alphanumeric identifier for the table.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.Table(
        )
    if FLAGS['attribution'].present:
      request.attribution = FLAGS.attribution.decode('utf8')
    if FLAGS['attributionLink'].present:
      request.attributionLink = FLAGS.attributionLink.decode('utf8')
    if FLAGS['baseTableIds'].present:
      request.baseTableIds = [x.decode('utf8') for x in FLAGS.baseTableIds]
    if FLAGS['columns'].present:
      request.columns = [apitools_base.JsonToMessage(messages.Column, x) for x in FLAGS.columns]
    if FLAGS['description'].present:
      request.description = FLAGS.description.decode('utf8')
    if FLAGS['isExportable'].present:
      request.isExportable = FLAGS.isExportable
    if FLAGS['kind'].present:
      request.kind = FLAGS.kind.decode('utf8')
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    if FLAGS['sql'].present:
      request.sql = FLAGS.sql.decode('utf8')
    if FLAGS['tableId'].present:
      request.tableId = FLAGS.tableId.decode('utf8')
    result = client.table.Insert(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TableList(apitools_base_cli.NewCmd):
  """Command wrapping table.List."""

  usage = """table_list"""

  def __init__(self, name, fv):
    super(TableList, self).__init__(name, fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Maximum number of styles to return. Optional. Default is 5.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        u'Continuation token specifying which result page to return. '
        u'Optional.',
        flag_values=fv)

  def RunWithArgs(self):
    """Retrieves a list of tables a user owns.

    Flags:
      maxResults: Maximum number of styles to return. Optional. Default is 5.
      pageToken: Continuation token specifying which result page to return.
        Optional.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTableListRequest(
        )
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    result = client.table.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TablePatch(apitools_base_cli.NewCmd):
  """Command wrapping table.Patch."""

  usage = """table_patch <tableId>"""

  def __init__(self, name, fv):
    super(TablePatch, self).__init__(name, fv)
    flags.DEFINE_boolean(
        'replaceViewDefinition',
        None,
        u'Should the view definition also be updated? The specified view '
        u'definition replaces the existing one. Only a view can be updated '
        u'with a new definition.',
        flag_values=fv)
    flags.DEFINE_string(
        'table',
        None,
        u'A Table resource to be passed as the request body.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Updates an existing table. Unless explicitly requested, only the name,
    description, and attribution will be updated. This method supports patch
    semantics.

    Args:
      tableId: ID of the table that is being updated.

    Flags:
      replaceViewDefinition: Should the view definition also be updated? The
        specified view definition replaces the existing one. Only a view can
        be updated with a new definition.
      table: A Table resource to be passed as the request body.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTablePatchRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['replaceViewDefinition'].present:
      request.replaceViewDefinition = FLAGS.replaceViewDefinition
    if FLAGS['table'].present:
      request.table = apitools_base.JsonToMessage(messages.Table, FLAGS.table)
    result = client.table.Patch(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TableUpdate(apitools_base_cli.NewCmd):
  """Command wrapping table.Update."""

  usage = """table_update <tableId>"""

  def __init__(self, name, fv):
    super(TableUpdate, self).__init__(name, fv)
    flags.DEFINE_boolean(
        'replaceViewDefinition',
        None,
        u'Should the view definition also be updated? The specified view '
        u'definition replaces the existing one. Only a view can be updated '
        u'with a new definition.',
        flag_values=fv)
    flags.DEFINE_string(
        'table',
        None,
        u'A Table resource to be passed as the request body.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Updates an existing table. Unless explicitly requested, only the name,
    description, and attribution will be updated.

    Args:
      tableId: ID of the table that is being updated.

    Flags:
      replaceViewDefinition: Should the view definition also be updated? The
        specified view definition replaces the existing one. Only a view can
        be updated with a new definition.
      table: A Table resource to be passed as the request body.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTableUpdateRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['replaceViewDefinition'].present:
      request.replaceViewDefinition = FLAGS.replaceViewDefinition
    if FLAGS['table'].present:
      request.table = apitools_base.JsonToMessage(messages.Table, FLAGS.table)
    result = client.table.Update(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TaskDelete(apitools_base_cli.NewCmd):
  """Command wrapping task.Delete."""

  usage = """task_delete <tableId> <taskId>"""

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

  def RunWithArgs(self, tableId, taskId):
    """Deletes the task, unless already started.

    Args:
      tableId: Table from which the task is being deleted.
      taskId: A string attribute.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTaskDeleteRequest(
        tableId=tableId.decode('utf8'),
        taskId=taskId.decode('utf8'),
        )
    result = client.task.Delete(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TaskGet(apitools_base_cli.NewCmd):
  """Command wrapping task.Get."""

  usage = """task_get <tableId> <taskId>"""

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

  def RunWithArgs(self, tableId, taskId):
    """Retrieves a specific task by its id.

    Args:
      tableId: Table to which the task belongs.
      taskId: A string attribute.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTaskGetRequest(
        tableId=tableId.decode('utf8'),
        taskId=taskId.decode('utf8'),
        )
    result = client.task.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TaskList(apitools_base_cli.NewCmd):
  """Command wrapping task.List."""

  usage = """task_list <tableId>"""

  def __init__(self, name, fv):
    super(TaskList, self).__init__(name, fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Maximum number of columns to return. Optional. Default is 5.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        'A string attribute.',
        flag_values=fv)
    flags.DEFINE_integer(
        'startIndex',
        None,
        'A integer attribute.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Retrieves a list of tasks.

    Args:
      tableId: Table whose tasks are being listed.

    Flags:
      maxResults: Maximum number of columns to return. Optional. Default is 5.
      pageToken: A string attribute.
      startIndex: A integer attribute.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTaskListRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    if FLAGS['startIndex'].present:
      request.startIndex = FLAGS.startIndex
    result = client.task.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TemplateDelete(apitools_base_cli.NewCmd):
  """Command wrapping template.Delete."""

  usage = """template_delete <tableId> <templateId>"""

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

  def RunWithArgs(self, tableId, templateId):
    """Deletes a template

    Args:
      tableId: Table from which the template is being deleted
      templateId: Identifier for the template which is being deleted
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTemplateDeleteRequest(
        tableId=tableId.decode('utf8'),
        templateId=templateId,
        )
    result = client.template.Delete(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TemplateGet(apitools_base_cli.NewCmd):
  """Command wrapping template.Get."""

  usage = """template_get <tableId> <templateId>"""

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

  def RunWithArgs(self, tableId, templateId):
    """Retrieves a specific template by its id

    Args:
      tableId: Table to which the template belongs
      templateId: Identifier for the template that is being requested
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTemplateGetRequest(
        tableId=tableId.decode('utf8'),
        templateId=templateId,
        )
    result = client.template.Get(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TemplateInsert(apitools_base_cli.NewCmd):
  """Command wrapping template.Insert."""

  usage = """template_insert <tableId>"""

  def __init__(self, name, fv):
    super(TemplateInsert, self).__init__(name, fv)
    flags.DEFINE_string(
        'automaticColumnNames',
        None,
        u'List of columns from which the template is to be automatically '
        u'constructed. Only one of body or automaticColumns can be specified.',
        flag_values=fv)
    flags.DEFINE_string(
        'body',
        None,
        u'Body of the template. It contains HTML with {column_name} to insert'
        u' values from a particular column. The body is sanitized to remove '
        u'certain tags, e.g., script. Only one of body or automaticColumns '
        u'can be specified.',
        flag_values=fv)
    flags.DEFINE_string(
        'kind',
        u'fusiontables#template',
        u'Type name: a template for the info window contents. The template '
        u'can either include an HTML body or a list of columns from which the'
        u' template is computed automatically.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Optional name assigned to a template.',
        flag_values=fv)
    flags.DEFINE_integer(
        'templateId',
        None,
        u'Identifier for the template, unique within the context of a '
        u'particular table.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Creates a new template for the table.

    Args:
      tableId: Identifier for the table for which the template is defined.

    Flags:
      automaticColumnNames: List of columns from which the template is to be
        automatically constructed. Only one of body or automaticColumns can be
        specified.
      body: Body of the template. It contains HTML with {column_name} to
        insert values from a particular column. The body is sanitized to
        remove certain tags, e.g., script. Only one of body or
        automaticColumns can be specified.
      kind: Type name: a template for the info window contents. The template
        can either include an HTML body or a list of columns from which the
        template is computed automatically.
      name: Optional name assigned to a template.
      templateId: Identifier for the template, unique within the context of a
        particular table.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.Template(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['automaticColumnNames'].present:
      request.automaticColumnNames = [x.decode('utf8') for x in FLAGS.automaticColumnNames]
    if FLAGS['body'].present:
      request.body = FLAGS.body.decode('utf8')
    if FLAGS['kind'].present:
      request.kind = FLAGS.kind.decode('utf8')
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    if FLAGS['templateId'].present:
      request.templateId = FLAGS.templateId
    result = client.template.Insert(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TemplateList(apitools_base_cli.NewCmd):
  """Command wrapping template.List."""

  usage = """template_list <tableId>"""

  def __init__(self, name, fv):
    super(TemplateList, self).__init__(name, fv)
    flags.DEFINE_integer(
        'maxResults',
        None,
        u'Maximum number of templates to return. Optional. Default is 5.',
        flag_values=fv)
    flags.DEFINE_string(
        'pageToken',
        None,
        u'Continuation token specifying which results page to return. '
        u'Optional.',
        flag_values=fv)

  def RunWithArgs(self, tableId):
    """Retrieves a list of templates.

    Args:
      tableId: Identifier for the table whose templates are being requested

    Flags:
      maxResults: Maximum number of templates to return. Optional. Default is
        5.
      pageToken: Continuation token specifying which results page to return.
        Optional.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.FusiontablesTemplateListRequest(
        tableId=tableId.decode('utf8'),
        )
    if FLAGS['maxResults'].present:
      request.maxResults = FLAGS.maxResults
    if FLAGS['pageToken'].present:
      request.pageToken = FLAGS.pageToken.decode('utf8')
    result = client.template.List(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TemplatePatch(apitools_base_cli.NewCmd):
  """Command wrapping template.Patch."""

  usage = """template_patch <tableId> <templateId>"""

  def __init__(self, name, fv):
    super(TemplatePatch, self).__init__(name, fv)
    flags.DEFINE_string(
        'automaticColumnNames',
        None,
        u'List of columns from which the template is to be automatically '
        u'constructed. Only one of body or automaticColumns can be specified.',
        flag_values=fv)
    flags.DEFINE_string(
        'body',
        None,
        u'Body of the template. It contains HTML with {column_name} to insert'
        u' values from a particular column. The body is sanitized to remove '
        u'certain tags, e.g., script. Only one of body or automaticColumns '
        u'can be specified.',
        flag_values=fv)
    flags.DEFINE_string(
        'kind',
        u'fusiontables#template',
        u'Type name: a template for the info window contents. The template '
        u'can either include an HTML body or a list of columns from which the'
        u' template is computed automatically.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Optional name assigned to a template.',
        flag_values=fv)

  def RunWithArgs(self, tableId, templateId):
    """Updates an existing template. This method supports patch semantics.

    Args:
      tableId: Identifier for the table for which the template is defined.
      templateId: Identifier for the template, unique within the context of a
        particular table.

    Flags:
      automaticColumnNames: List of columns from which the template is to be
        automatically constructed. Only one of body or automaticColumns can be
        specified.
      body: Body of the template. It contains HTML with {column_name} to
        insert values from a particular column. The body is sanitized to
        remove certain tags, e.g., script. Only one of body or
        automaticColumns can be specified.
      kind: Type name: a template for the info window contents. The template
        can either include an HTML body or a list of columns from which the
        template is computed automatically.
      name: Optional name assigned to a template.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.Template(
        tableId=tableId.decode('utf8'),
        templateId=templateId,
        )
    if FLAGS['automaticColumnNames'].present:
      request.automaticColumnNames = [x.decode('utf8') for x in FLAGS.automaticColumnNames]
    if FLAGS['body'].present:
      request.body = FLAGS.body.decode('utf8')
    if FLAGS['kind'].present:
      request.kind = FLAGS.kind.decode('utf8')
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    result = client.template.Patch(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


class TemplateUpdate(apitools_base_cli.NewCmd):
  """Command wrapping template.Update."""

  usage = """template_update <tableId> <templateId>"""

  def __init__(self, name, fv):
    super(TemplateUpdate, self).__init__(name, fv)
    flags.DEFINE_string(
        'automaticColumnNames',
        None,
        u'List of columns from which the template is to be automatically '
        u'constructed. Only one of body or automaticColumns can be specified.',
        flag_values=fv)
    flags.DEFINE_string(
        'body',
        None,
        u'Body of the template. It contains HTML with {column_name} to insert'
        u' values from a particular column. The body is sanitized to remove '
        u'certain tags, e.g., script. Only one of body or automaticColumns '
        u'can be specified.',
        flag_values=fv)
    flags.DEFINE_string(
        'kind',
        u'fusiontables#template',
        u'Type name: a template for the info window contents. The template '
        u'can either include an HTML body or a list of columns from which the'
        u' template is computed automatically.',
        flag_values=fv)
    flags.DEFINE_string(
        'name',
        None,
        u'Optional name assigned to a template.',
        flag_values=fv)

  def RunWithArgs(self, tableId, templateId):
    """Updates an existing template

    Args:
      tableId: Identifier for the table for which the template is defined.
      templateId: Identifier for the template, unique within the context of a
        particular table.

    Flags:
      automaticColumnNames: List of columns from which the template is to be
        automatically constructed. Only one of body or automaticColumns can be
        specified.
      body: Body of the template. It contains HTML with {column_name} to
        insert values from a particular column. The body is sanitized to
        remove certain tags, e.g., script. Only one of body or
        automaticColumns can be specified.
      kind: Type name: a template for the info window contents. The template
        can either include an HTML body or a list of columns from which the
        template is computed automatically.
      name: Optional name assigned to a template.
    """
    client = GetClientFromFlags()
    global_params = GetGlobalParamsFromFlags()
    request = messages.Template(
        tableId=tableId.decode('utf8'),
        templateId=templateId,
        )
    if FLAGS['automaticColumnNames'].present:
      request.automaticColumnNames = [x.decode('utf8') for x in FLAGS.automaticColumnNames]
    if FLAGS['body'].present:
      request.body = FLAGS.body.decode('utf8')
    if FLAGS['kind'].present:
      request.kind = FLAGS.kind.decode('utf8')
    if FLAGS['name'].present:
      request.name = FLAGS.name.decode('utf8')
    result = client.template.Update(
        request, global_params=global_params)
    print apitools_base_cli.FormatOutput(result)


def main(_):
  appcommands.AddCmd('pyshell', PyShell)
  appcommands.AddCmd('column_delete', ColumnDelete)
  appcommands.AddCmd('column_get', ColumnGet)
  appcommands.AddCmd('column_insert', ColumnInsert)
  appcommands.AddCmd('column_list', ColumnList)
  appcommands.AddCmd('column_patch', ColumnPatch)
  appcommands.AddCmd('column_update', ColumnUpdate)
  appcommands.AddCmd('query_sql', QuerySql)
  appcommands.AddCmd('query_sqlGet', QuerySqlGet)
  appcommands.AddCmd('style_delete', StyleDelete)
  appcommands.AddCmd('style_get', StyleGet)
  appcommands.AddCmd('style_insert', StyleInsert)
  appcommands.AddCmd('style_list', StyleList)
  appcommands.AddCmd('style_patch', StylePatch)
  appcommands.AddCmd('style_update', StyleUpdate)
  appcommands.AddCmd('table_copy', TableCopy)
  appcommands.AddCmd('table_delete', TableDelete)
  appcommands.AddCmd('table_get', TableGet)
  appcommands.AddCmd('table_importRows', TableImportRows)
  appcommands.AddCmd('table_importTable', TableImportTable)
  appcommands.AddCmd('table_insert', TableInsert)
  appcommands.AddCmd('table_list', TableList)
  appcommands.AddCmd('table_patch', TablePatch)
  appcommands.AddCmd('table_update', TableUpdate)
  appcommands.AddCmd('task_delete', TaskDelete)
  appcommands.AddCmd('task_get', TaskGet)
  appcommands.AddCmd('task_list', TaskList)
  appcommands.AddCmd('template_delete', TemplateDelete)
  appcommands.AddCmd('template_get', TemplateGet)
  appcommands.AddCmd('template_insert', TemplateInsert)
  appcommands.AddCmd('template_list', TemplateList)
  appcommands.AddCmd('template_patch', TemplatePatch)
  appcommands.AddCmd('template_update', TemplateUpdate)

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


run_main = apitools_base_cli.run_main

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