# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""The runtime-configs variables set command."""

import sys
from googlecloudsdk.api_lib.deployment_manager.runtime_configs import util
from googlecloudsdk.api_lib.util import http_error_handler
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.deployment_manager.runtime_configs import flags
from googlecloudsdk.core import log
from googlecloudsdk.third_party.apitools.base.py import exceptions as apitools_exceptions


class Set(base.CreateCommand):
  """Create or update variable resources.

  This command creates or updates a variable resource, setting its value to
  the specified string or file contents.
  """

  detailed_help = {
      'DESCRIPTION': '{description}',
      'EXAMPLES': """\
          To create or update a variable named "my-var", run:

            $ {command} --config-name my-config my-var "my value"

          To create or update a variable with a hierarchical name, such as
          "results/task1", run:

            $ {command} --config-name my-config results/task1 "my value"

          To create a variable, but fail if it already exists, run:

            $ {command} --config-name my-config my-var "my-value" --fail-if-present

          To update a variable, but fail if it does not exist, run:

            $ {command} --config-name my-config my-var "my-value" --fail-if-absent

          If the variable's value parameter is not specified, the value will be
          read from standard input. This allows setting variables to large values
          or values that contain non-printable characters. The variable value
          will be automatically base64-encoded. For example, to set a variable's
          value to the contents of a file, run:

            $ cat my-file | {command} --config-name my-config my-var
          """,
  }

  @staticmethod
  def Args(parser):
    """Args is called by calliope to gather arguments for this command.

    Args:
      parser: An argparse parser that you can use to add arguments that go
          on the command line after this command. Positional arguments are
          allowed.
    """
    flags.AddConfigFlag(parser)

    fail_group = parser.add_mutually_exclusive_group()
    fail_group.add_argument(
        '--fail-if-present',
        help='Fail if a variable with the specified name already exists.',
        action='store_true')
    fail_group.add_argument(
        '--fail-if-absent',
        help='Fail if a variable with the specified name does not exist.',
        action='store_true')

    parser.add_argument('name', help='The variable name.')
    parser.add_argument(
        'value',
        nargs='?',
        default=None,
        help=(
            'The variable value. If absent, the value will be read from stdin. '
            'The value is automatically base64-encoded.'))

  def Collection(self):
    """Returns the default collection path string.

    Returns:
      The default collection path string.
    """
    return 'runtimeconfig.variables'

  @http_error_handler.HandleHttpErrors
  def Run(self, args):
    """Run 'runtime-configs variables set'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      The new variable.

    Raises:
      HttpException: An http error response was received while executing api
          request.
    """
    var_resource = util.ParseVariableName(args.name, args)
    if args.value is None:
      log.status.Print('No value argument specified; reading value from stdin.')
      value = sys.stdin.read()
    else:
      value = args.value

    if args.fail_if_absent:
      # Update case
      return self._Update(args, var_resource, value)
    else:
      # Either create or create-or-update
      try:
        return self._Create(args, var_resource, value)
      except apitools_exceptions.HttpError as error:
        # If --fail-if-present was not specified, and we got an
        # Already Exists error, try updating instead.
        if not args.fail_if_present and util.IsAlreadyExistsError(error):
          return self._Update(args, var_resource, value)

        # If --fail-if-present was specified, or some other error
        # occurred, re-raise the error.
        raise

  def _Create(self, args, var_resource, value):
    variable_client = util.VariableClient()
    messages = util.Messages()

    project = var_resource.projectsId
    config = var_resource.configsId
    name = var_resource.Name()

    result = variable_client.Create(
        messages.RuntimeconfigProjectsConfigsVariablesCreateRequest(
            projectsId=project,
            configsId=config,
            variable=messages.Variable(
                name=util.VariablePath(project, config, name),
                value=value
            )
        )
    )

    log.CreatedResource(var_resource)
    return util.FormatVariable(result)

  def _Update(self, args, var_resource, value):
    variable_client = util.VariableClient()
    messages = util.Messages()

    project = var_resource.projectsId
    config = var_resource.configsId
    name = var_resource.Name()

    result = variable_client.Update(
        messages.RuntimeconfigProjectsConfigsVariablesUpdateRequest(
            projectsId=project,
            configsId=config,
            variablesId=name,
            variable=messages.Variable(
                name=util.VariablePath(project, config, name),
                value=value
            )
        )
    )

    log.UpdatedResource(var_resource)
    return util.FormatVariable(result)
