# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. 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.
"""API wrapper for `gcloud service-extensions wasm-plugin` commands."""


from googlecloudsdk.api_lib.service_extensions import util
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources


class Client:
  """API client for WasmPlugin commands.

  Attributes:
    messages: API messages class, The Networkservices API messages.
  """

  def __init__(self, release_track):
    self._client = util.GetClientInstance(release_track)
    self._wasm_plugin_client = self._client.projects_locations_wasmPlugins
    self._operations_client = self._client.projects_locations_operations
    self.messages = self._client.MESSAGES_MODULE
    self._resource_parser = resources.Registry()
    self._resource_parser.RegisterApiByName(
        'networkservices', util.API_VERSION_FOR_TRACK.get(release_track)
    )
    self._release_track = release_track

  def CreateWasmPlugin(
      self,
      name,
      parent,
      description=None,
      labels=None,
      log_config=None,
      main_version=None,
      versions=None,
      kms_key_name=None,
  ):
    """Calls the CreateWasmPlugin API."""
    if self._release_track in [base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA]:
      wasm_plugin = self.messages.WasmPlugin(
          description=description,
          labels=labels,
          logConfig=log_config,
          mainVersionId=main_version,
          versions=versions,
          kmsKeyName=kms_key_name,
      )
    else:
      wasm_plugin = self.messages.WasmPlugin(
          description=description,
          labels=labels,
          logConfig=log_config,
          mainVersionId=main_version,
          versions=versions,
      )
    request = (
        self.messages.NetworkservicesProjectsLocationsWasmPluginsCreateRequest(
            parent=parent,
            wasmPluginId=name,
            wasmPlugin=wasm_plugin,
        )
    )
    return self._wasm_plugin_client.Create(request)

  def UpdateWasmPlugin(
      self,
      name,
      main_version,
      update_mask=None,
      description=None,
      labels=None,
      log_config=None,
      kms_key_name=None,
  ):
    """Calls the UpdateWasmPlugin API."""
    if self._release_track in [base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA]:
      wasm_plugin = self.messages.WasmPlugin(
          mainVersionId=main_version,
          description=description,
          labels=labels,
          logConfig=log_config,
          kmsKeyName=kms_key_name,
      )
    else:
      wasm_plugin = self.messages.WasmPlugin(
          mainVersionId=main_version,
          description=description,
          labels=labels,
          logConfig=log_config,
      )
    request = (
        self.messages.NetworkservicesProjectsLocationsWasmPluginsPatchRequest(
            name=name,
            updateMask=update_mask,
            wasmPlugin=wasm_plugin,
        )
    )
    return self._wasm_plugin_client.Patch(request)

  def PrepareVersionDetailsForSingleVersion(
      self, version_id, image, plugin_config_data, plugin_config_uri
  ):
    if version_id is None:
      return None
    return self.messages.WasmPlugin.VersionsValue(
        additionalProperties=[
            self.messages.WasmPlugin.VersionsValue.AdditionalProperty(
                key=version_id,
                value=self.messages.WasmPluginVersionDetails(
                    imageUri=image,
                    pluginConfigData=plugin_config_data,
                    pluginConfigUri=plugin_config_uri,
                ),
            )
        ]
    )

  def WaitForOperation(
      self,
      operation_ref,
      message,
  ):
    """Waits for the opration to complete and returns the result of the operation.

    Args:
      operation_ref: A Resource describing the Operation.
      message: The message to display to the user while they wait.

    Returns:
      result of result_service.Get request for the provided operation.
    """

    op_resource = resources.REGISTRY.ParseRelativeName(
        operation_ref.name,
        collection='networkservices.projects.locations.operations',
    )
    poller = waiter.CloudOperationPoller(
        self._wasm_plugin_client, self._operations_client
    )
    return waiter.WaitFor(
        poller,
        op_resource,
        message,
    )
