<?php
/*
 * Copyright 2023 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/*
 * GENERATED CODE WARNING
 * Generated by gapic-generator-php from the file
 * https://github.com/googleapis/googleapis/blob/master/google/cloud/dialogflow/cx/v3/intent.proto
 * Updates to the above are reflected here through a refresh process.
 */

namespace Google\Cloud\Dialogflow\Cx\V3\Gapic;

use Google\ApiCore\ApiException;
use Google\ApiCore\Call;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\GapicClientTrait;
use Google\ApiCore\LongRunning\OperationsClient;
use Google\ApiCore\OperationResponse;
use Google\ApiCore\PathTemplate;
use Google\ApiCore\RequestParamsHeaderDescriptor;
use Google\ApiCore\RetrySettings;
use Google\ApiCore\Transport\TransportInterface;
use Google\ApiCore\ValidationException;
use Google\Auth\FetchAuthTokenInterface;
use Google\Cloud\Dialogflow\Cx\V3\CreateIntentRequest;
use Google\Cloud\Dialogflow\Cx\V3\DeleteIntentRequest;
use Google\Cloud\Dialogflow\Cx\V3\ExportIntentsMetadata;
use Google\Cloud\Dialogflow\Cx\V3\ExportIntentsRequest;
use Google\Cloud\Dialogflow\Cx\V3\ExportIntentsResponse;
use Google\Cloud\Dialogflow\Cx\V3\GetIntentRequest;
use Google\Cloud\Dialogflow\Cx\V3\ImportIntentsMetadata;
use Google\Cloud\Dialogflow\Cx\V3\ImportIntentsRequest;
use Google\Cloud\Dialogflow\Cx\V3\ImportIntentsResponse;
use Google\Cloud\Dialogflow\Cx\V3\InlineSource;
use Google\Cloud\Dialogflow\Cx\V3\Intent;
use Google\Cloud\Dialogflow\Cx\V3\ListIntentsRequest;
use Google\Cloud\Dialogflow\Cx\V3\ListIntentsResponse;
use Google\Cloud\Dialogflow\Cx\V3\UpdateIntentRequest;
use Google\Cloud\Location\GetLocationRequest;
use Google\Cloud\Location\ListLocationsRequest;
use Google\Cloud\Location\ListLocationsResponse;
use Google\Cloud\Location\Location;
use Google\LongRunning\Operation;
use Google\Protobuf\FieldMask;
use Google\Protobuf\GPBEmpty;

/**
 * Service Description: Service for managing [Intents][google.cloud.dialogflow.cx.v3.Intent].
 *
 * This class provides the ability to make remote calls to the backing service through method
 * calls that map to API methods. Sample code to get started:
 *
 * ```
 * $intentsClient = new IntentsClient();
 * try {
 *     $formattedParent = $intentsClient->agentName('[PROJECT]', '[LOCATION]', '[AGENT]');
 *     $intent = new Intent();
 *     $response = $intentsClient->createIntent($formattedParent, $intent);
 * } finally {
 *     $intentsClient->close();
 * }
 * ```
 *
 * Many parameters require resource names to be formatted in a particular way. To
 * assist with these names, this class includes a format method for each type of
 * name, and additionally a parseName method to extract the individual identifiers
 * contained within formatted names that are returned by the API.
 */
class IntentsGapicClient
{
    use GapicClientTrait;

    /** The name of the service. */
    const SERVICE_NAME = 'google.cloud.dialogflow.cx.v3.Intents';

    /** The default address of the service. */
    const SERVICE_ADDRESS = 'dialogflow.googleapis.com';

    /** The default port of the service. */
    const DEFAULT_SERVICE_PORT = 443;

    /** The name of the code generator, to be included in the agent header. */
    const CODEGEN_NAME = 'gapic';

    /** The default scopes required by the service. */
    public static $serviceScopes = [
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/dialogflow',
    ];

    private static $agentNameTemplate;

    private static $entityTypeNameTemplate;

    private static $intentNameTemplate;

    private static $pathTemplateMap;

    private $operationsClient;

    private static function getClientDefaults()
    {
        return [
            'serviceName' => self::SERVICE_NAME,
            'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT,
            'clientConfig' => __DIR__ . '/../resources/intents_client_config.json',
            'descriptorsConfigPath' => __DIR__ . '/../resources/intents_descriptor_config.php',
            'gcpApiConfigPath' => __DIR__ . '/../resources/intents_grpc_config.json',
            'credentialsConfig' => [
                'defaultScopes' => self::$serviceScopes,
            ],
            'transportConfig' => [
                'rest' => [
                    'restClientConfigPath' => __DIR__ . '/../resources/intents_rest_client_config.php',
                ],
            ],
        ];
    }

    private static function getAgentNameTemplate()
    {
        if (self::$agentNameTemplate == null) {
            self::$agentNameTemplate = new PathTemplate('projects/{project}/locations/{location}/agents/{agent}');
        }

        return self::$agentNameTemplate;
    }

    private static function getEntityTypeNameTemplate()
    {
        if (self::$entityTypeNameTemplate == null) {
            self::$entityTypeNameTemplate = new PathTemplate('projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}');
        }

        return self::$entityTypeNameTemplate;
    }

    private static function getIntentNameTemplate()
    {
        if (self::$intentNameTemplate == null) {
            self::$intentNameTemplate = new PathTemplate('projects/{project}/locations/{location}/agents/{agent}/intents/{intent}');
        }

        return self::$intentNameTemplate;
    }

    private static function getPathTemplateMap()
    {
        if (self::$pathTemplateMap == null) {
            self::$pathTemplateMap = [
                'agent' => self::getAgentNameTemplate(),
                'entityType' => self::getEntityTypeNameTemplate(),
                'intent' => self::getIntentNameTemplate(),
            ];
        }

        return self::$pathTemplateMap;
    }

    /**
     * Formats a string containing the fully-qualified path to represent a agent
     * resource.
     *
     * @param string $project
     * @param string $location
     * @param string $agent
     *
     * @return string The formatted agent resource.
     */
    public static function agentName($project, $location, $agent)
    {
        return self::getAgentNameTemplate()->render([
            'project' => $project,
            'location' => $location,
            'agent' => $agent,
        ]);
    }

    /**
     * Formats a string containing the fully-qualified path to represent a entity_type
     * resource.
     *
     * @param string $project
     * @param string $location
     * @param string $agent
     * @param string $entityType
     *
     * @return string The formatted entity_type resource.
     */
    public static function entityTypeName($project, $location, $agent, $entityType)
    {
        return self::getEntityTypeNameTemplate()->render([
            'project' => $project,
            'location' => $location,
            'agent' => $agent,
            'entity_type' => $entityType,
        ]);
    }

    /**
     * Formats a string containing the fully-qualified path to represent a intent
     * resource.
     *
     * @param string $project
     * @param string $location
     * @param string $agent
     * @param string $intent
     *
     * @return string The formatted intent resource.
     */
    public static function intentName($project, $location, $agent, $intent)
    {
        return self::getIntentNameTemplate()->render([
            'project' => $project,
            'location' => $location,
            'agent' => $agent,
            'intent' => $intent,
        ]);
    }

    /**
     * Parses a formatted name string and returns an associative array of the components in the name.
     * The following name formats are supported:
     * Template: Pattern
     * - agent: projects/{project}/locations/{location}/agents/{agent}
     * - entityType: projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}
     * - intent: projects/{project}/locations/{location}/agents/{agent}/intents/{intent}
     *
     * The optional $template argument can be supplied to specify a particular pattern,
     * and must match one of the templates listed above. If no $template argument is
     * provided, or if the $template argument does not match one of the templates
     * listed, then parseName will check each of the supported templates, and return
     * the first match.
     *
     * @param string $formattedName The formatted name string
     * @param string $template      Optional name of template to match
     *
     * @return array An associative array from name component IDs to component values.
     *
     * @throws ValidationException If $formattedName could not be matched.
     */
    public static function parseName($formattedName, $template = null)
    {
        $templateMap = self::getPathTemplateMap();
        if ($template) {
            if (!isset($templateMap[$template])) {
                throw new ValidationException("Template name $template does not exist");
            }

            return $templateMap[$template]->match($formattedName);
        }

        foreach ($templateMap as $templateName => $pathTemplate) {
            try {
                return $pathTemplate->match($formattedName);
            } catch (ValidationException $ex) {
                // Swallow the exception to continue trying other path templates
            }
        }

        throw new ValidationException("Input did not match any known format. Input: $formattedName");
    }

    /**
     * Return an OperationsClient object with the same endpoint as $this.
     *
     * @return OperationsClient
     */
    public function getOperationsClient()
    {
        return $this->operationsClient;
    }

    /**
     * Resume an existing long running operation that was previously started by a long
     * running API method. If $methodName is not provided, or does not match a long
     * running API method, then the operation can still be resumed, but the
     * OperationResponse object will not deserialize the final response.
     *
     * @param string $operationName The name of the long running operation
     * @param string $methodName    The name of the method used to start the operation
     *
     * @return OperationResponse
     */
    public function resumeOperation($operationName, $methodName = null)
    {
        $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : [];
        $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options);
        $operation->reload();
        return $operation;
    }

    /**
     * Constructor.
     *
     * @param array $options {
     *     Optional. Options for configuring the service API wrapper.
     *
     *     @type string $apiEndpoint
     *           The address of the API remote host. May optionally include the port, formatted
     *           as "<uri>:<port>". Default 'dialogflow.googleapis.com:443'.
     *     @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials
     *           The credentials to be used by the client to authorize API calls. This option
     *           accepts either a path to a credentials file, or a decoded credentials file as a
     *           PHP array.
     *           *Advanced usage*: In addition, this option can also accept a pre-constructed
     *           {@see \Google\Auth\FetchAuthTokenInterface} object or
     *           {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these
     *           objects are provided, any settings in $credentialsConfig will be ignored.
     *     @type array $credentialsConfig
     *           Options used to configure credentials, including auth token caching, for the
     *           client. For a full list of supporting configuration options, see
     *           {@see \Google\ApiCore\CredentialsWrapper::build()} .
     *     @type bool $disableRetries
     *           Determines whether or not retries defined by the client configuration should be
     *           disabled. Defaults to `false`.
     *     @type string|array $clientConfig
     *           Client method configuration, including retry settings. This option can be either
     *           a path to a JSON file, or a PHP array containing the decoded JSON data. By
     *           default this settings points to the default client config file, which is
     *           provided in the resources folder.
     *     @type string|TransportInterface $transport
     *           The transport used for executing network requests. May be either the string
     *           `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system.
     *           *Advanced usage*: Additionally, it is possible to pass in an already
     *           instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note
     *           that when this object is provided, any settings in $transportConfig, and any
     *           $apiEndpoint setting, will be ignored.
     *     @type array $transportConfig
     *           Configuration options that will be used to construct the transport. Options for
     *           each supported transport type should be passed in a key for that transport. For
     *           example:
     *           $transportConfig = [
     *               'grpc' => [...],
     *               'rest' => [...],
     *           ];
     *           See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and
     *           {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the
     *           supported options.
     *     @type callable $clientCertSource
     *           A callable which returns the client cert as a string. This can be used to
     *           provide a certificate and private key to the transport layer for mTLS.
     * }
     *
     * @throws ValidationException
     */
    public function __construct(array $options = [])
    {
        $clientOptions = $this->buildClientOptions($options);
        $this->setClientOptions($clientOptions);
        $this->operationsClient = $this->createOperationsClient($clientOptions);
    }

    /**
     * Creates an intent in the specified agent.
     *
     * Note: You should always train a flow prior to sending it queries. See the
     * [training
     * documentation](https://cloud.google.com/dialogflow/cx/docs/concept/training).
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $formattedParent = $intentsClient->agentName('[PROJECT]', '[LOCATION]', '[AGENT]');
     *     $intent = new Intent();
     *     $response = $intentsClient->createIntent($formattedParent, $intent);
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The agent to create an intent for.
     *                             Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>`.
     * @param Intent $intent       Required. The intent to create.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type string $languageCode
     *           The language of the following fields in `intent`:
     *
     *           *   `Intent.training_phrases.parts.text`
     *
     *           If not specified, the agent's default language is used.
     *           [Many
     *           languages](https://cloud.google.com/dialogflow/cx/docs/reference/language)
     *           are supported.
     *           Note: languages must be enabled in the agent before they can be used.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Dialogflow\Cx\V3\Intent
     *
     * @throws ApiException if the remote call fails
     */
    public function createIntent($parent, $intent, array $optionalArgs = [])
    {
        $request = new CreateIntentRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $request->setIntent($intent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['languageCode'])) {
            $request->setLanguageCode($optionalArgs['languageCode']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('CreateIntent', Intent::class, $optionalArgs, $request)->wait();
    }

    /**
     * Deletes the specified intent.
     *
     * Note: You should always train a flow prior to sending it queries. See the
     * [training
     * documentation](https://cloud.google.com/dialogflow/cx/docs/concept/training).
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $formattedName = $intentsClient->intentName('[PROJECT]', '[LOCATION]', '[AGENT]', '[INTENT]');
     *     $intentsClient->deleteIntent($formattedName);
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the intent to delete.
     *                             Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
     *                             ID>/intents/<Intent ID>`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @throws ApiException if the remote call fails
     */
    public function deleteIntent($name, array $optionalArgs = [])
    {
        $request = new DeleteIntentRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('DeleteIntent', GPBEmpty::class, $optionalArgs, $request)->wait();
    }

    /**
     * Exports the selected intents.
     *
     * This method is a [long-running
     * operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation).
     * The returned `Operation` type has the following method-specific fields:
     *
     * - `metadata`:
     * [ExportIntentsMetadata][google.cloud.dialogflow.cx.v3.ExportIntentsMetadata]
     * - `response`:
     * [ExportIntentsResponse][google.cloud.dialogflow.cx.v3.ExportIntentsResponse]
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $formattedParent = $intentsClient->agentName('[PROJECT]', '[LOCATION]', '[AGENT]');
     *     $intents = [];
     *     $operationResponse = $intentsClient->exportIntents($formattedParent, $intents);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $intentsClient->exportIntents($formattedParent, $intents);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $intentsClient->resumeOperation($operationName, 'exportIntents');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param string   $parent       Required. The name of the parent agent to export intents.
     *                               Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
     *                               ID>`.
     * @param string[] $intents      Required. The name of the intents to export.
     *                               Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
     *                               ID>/intents/<Intent ID>`.
     * @param array    $optionalArgs {
     *     Optional.
     *
     *     @type string $intentsUri
     *           Optional. The [Google Cloud
     *           Storage](https://cloud.google.com/storage/docs/) URI to export the
     *           intents to. The format of this URI must be
     *           `gs://<bucket-name>/<object-name>`.
     *
     *           Dialogflow performs a write operation for the Cloud Storage object
     *           on the caller's behalf, so your request authentication must
     *           have write permissions for the object. For more information, see
     *           [Dialogflow access
     *           control](https://cloud.google.com/dialogflow/cx/docs/concept/access-control#storage).
     *     @type bool $intentsContentInline
     *           Optional. The option to return the serialized intents inline.
     *     @type int $dataFormat
     *           Optional. The data format of the exported intents. If not specified, `BLOB`
     *           is assumed.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Dialogflow\Cx\V3\ExportIntentsRequest\DataFormat}
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function exportIntents($parent, $intents, array $optionalArgs = [])
    {
        $request = new ExportIntentsRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $request->setIntents($intents);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['intentsUri'])) {
            $request->setIntentsUri($optionalArgs['intentsUri']);
        }

        if (isset($optionalArgs['intentsContentInline'])) {
            $request->setIntentsContentInline($optionalArgs['intentsContentInline']);
        }

        if (isset($optionalArgs['dataFormat'])) {
            $request->setDataFormat($optionalArgs['dataFormat']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('ExportIntents', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Retrieves the specified intent.
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $formattedName = $intentsClient->intentName('[PROJECT]', '[LOCATION]', '[AGENT]', '[INTENT]');
     *     $response = $intentsClient->getIntent($formattedName);
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the intent.
     *                             Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
     *                             ID>/intents/<Intent ID>`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type string $languageCode
     *           The language to retrieve the intent for. The following fields are language
     *           dependent:
     *
     *           *   `Intent.training_phrases.parts.text`
     *
     *           If not specified, the agent's default language is used.
     *           [Many
     *           languages](https://cloud.google.com/dialogflow/cx/docs/reference/language)
     *           are supported.
     *           Note: languages must be enabled in the agent before they can be used.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Dialogflow\Cx\V3\Intent
     *
     * @throws ApiException if the remote call fails
     */
    public function getIntent($name, array $optionalArgs = [])
    {
        $request = new GetIntentRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        if (isset($optionalArgs['languageCode'])) {
            $request->setLanguageCode($optionalArgs['languageCode']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('GetIntent', Intent::class, $optionalArgs, $request)->wait();
    }

    /**
     * Imports the specified intents into the agent.
     *
     * This method is a [long-running
     * operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation).
     * The returned `Operation` type has the following method-specific fields:
     *
     * - `metadata`:
     * [ImportIntentsMetadata][google.cloud.dialogflow.cx.v3.ImportIntentsMetadata]
     * - `response`:
     * [ImportIntentsResponse][google.cloud.dialogflow.cx.v3.ImportIntentsResponse]
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $formattedParent = $intentsClient->agentName('[PROJECT]', '[LOCATION]', '[AGENT]');
     *     $operationResponse = $intentsClient->importIntents($formattedParent);
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $intentsClient->importIntents($formattedParent);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $intentsClient->resumeOperation($operationName, 'importIntents');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The agent to import the intents into.
     *                             Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type string $intentsUri
     *           The [Google Cloud Storage](https://cloud.google.com/storage/docs/) URI
     *           to import intents from. The format of this URI must be
     *           `gs://<bucket-name>/<object-name>`.
     *
     *           Dialogflow performs a read operation for the Cloud Storage object
     *           on the caller's behalf, so your request authentication must
     *           have read permissions for the object. For more information, see
     *           [Dialogflow access
     *           control](https://cloud.google.com/dialogflow/cx/docs/concept/access-control#storage).
     *     @type InlineSource $intentsContent
     *           Uncompressed byte content of intents.
     *     @type int $mergeOption
     *           Merge option for importing intents. If not specified, `REJECT` is assumed.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Dialogflow\Cx\V3\ImportIntentsRequest\MergeOption}
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function importIntents($parent, array $optionalArgs = [])
    {
        $request = new ImportIntentsRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['intentsUri'])) {
            $request->setIntentsUri($optionalArgs['intentsUri']);
        }

        if (isset($optionalArgs['intentsContent'])) {
            $request->setIntentsContent($optionalArgs['intentsContent']);
        }

        if (isset($optionalArgs['mergeOption'])) {
            $request->setMergeOption($optionalArgs['mergeOption']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('ImportIntents', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Returns the list of all intents in the specified agent.
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $formattedParent = $intentsClient->agentName('[PROJECT]', '[LOCATION]', '[AGENT]');
     *     // Iterate over pages of elements
     *     $pagedResponse = $intentsClient->listIntents($formattedParent);
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $intentsClient->listIntents($formattedParent);
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The agent to list all intents for.
     *                             Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type string $languageCode
     *           The language to list intents for. The following fields are language
     *           dependent:
     *
     *           *   `Intent.training_phrases.parts.text`
     *
     *           If not specified, the agent's default language is used.
     *           [Many
     *           languages](https://cloud.google.com/dialogflow/cx/docs/reference/language)
     *           are supported.
     *           Note: languages must be enabled in the agent before they can be used.
     *     @type int $intentView
     *           The resource view to apply to the returned intent.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Dialogflow\Cx\V3\IntentView}
     *     @type int $pageSize
     *           The maximum number of resources contained in the underlying API
     *           response. The API may return fewer values in a page, even if
     *           there are additional values to be retrieved.
     *     @type string $pageToken
     *           A page token is used to specify a page of values to be returned.
     *           If no page token is specified (the default), the first page
     *           of values will be returned. Any page token used here must have
     *           been generated by a previous call to the API.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\PagedListResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function listIntents($parent, array $optionalArgs = [])
    {
        $request = new ListIntentsRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['languageCode'])) {
            $request->setLanguageCode($optionalArgs['languageCode']);
        }

        if (isset($optionalArgs['intentView'])) {
            $request->setIntentView($optionalArgs['intentView']);
        }

        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

        if (isset($optionalArgs['pageToken'])) {
            $request->setPageToken($optionalArgs['pageToken']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->getPagedListResponse('ListIntents', $optionalArgs, ListIntentsResponse::class, $request);
    }

    /**
     * Updates the specified intent.
     *
     * Note: You should always train a flow prior to sending it queries. See the
     * [training
     * documentation](https://cloud.google.com/dialogflow/cx/docs/concept/training).
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $intent = new Intent();
     *     $response = $intentsClient->updateIntent($intent);
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param Intent $intent       Required. The intent to update.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type string $languageCode
     *           The language of the following fields in `intent`:
     *
     *           *   `Intent.training_phrases.parts.text`
     *
     *           If not specified, the agent's default language is used.
     *           [Many
     *           languages](https://cloud.google.com/dialogflow/cx/docs/reference/language)
     *           are supported.
     *           Note: languages must be enabled in the agent before they can be used.
     *     @type FieldMask $updateMask
     *           The mask to control which fields get updated. If the mask is not present,
     *           all fields will be updated.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Dialogflow\Cx\V3\Intent
     *
     * @throws ApiException if the remote call fails
     */
    public function updateIntent($intent, array $optionalArgs = [])
    {
        $request = new UpdateIntentRequest();
        $requestParamHeaders = [];
        $request->setIntent($intent);
        $requestParamHeaders['intent.name'] = $intent->getName();
        if (isset($optionalArgs['languageCode'])) {
            $request->setLanguageCode($optionalArgs['languageCode']);
        }

        if (isset($optionalArgs['updateMask'])) {
            $request->setUpdateMask($optionalArgs['updateMask']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('UpdateIntent', Intent::class, $optionalArgs, $request)->wait();
    }

    /**
     * Gets information about a location.
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     $response = $intentsClient->getLocation();
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $name
     *           Resource name for the location.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Location\Location
     *
     * @throws ApiException if the remote call fails
     */
    public function getLocation(array $optionalArgs = [])
    {
        $request = new GetLocationRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['name'])) {
            $request->setName($optionalArgs['name']);
            $requestParamHeaders['name'] = $optionalArgs['name'];
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('GetLocation', Location::class, $optionalArgs, $request, Call::UNARY_CALL, 'google.cloud.location.Locations')->wait();
    }

    /**
     * Lists information about the supported locations for this service.
     *
     * Sample code:
     * ```
     * $intentsClient = new IntentsClient();
     * try {
     *     // Iterate over pages of elements
     *     $pagedResponse = $intentsClient->listLocations();
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $intentsClient->listLocations();
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $intentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $name
     *           The resource that owns the locations collection, if applicable.
     *     @type string $filter
     *           The standard list filter.
     *     @type int $pageSize
     *           The maximum number of resources contained in the underlying API
     *           response. The API may return fewer values in a page, even if
     *           there are additional values to be retrieved.
     *     @type string $pageToken
     *           A page token is used to specify a page of values to be returned.
     *           If no page token is specified (the default), the first page
     *           of values will be returned. Any page token used here must have
     *           been generated by a previous call to the API.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\PagedListResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function listLocations(array $optionalArgs = [])
    {
        $request = new ListLocationsRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['name'])) {
            $request->setName($optionalArgs['name']);
            $requestParamHeaders['name'] = $optionalArgs['name'];
        }

        if (isset($optionalArgs['filter'])) {
            $request->setFilter($optionalArgs['filter']);
        }

        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

        if (isset($optionalArgs['pageToken'])) {
            $request->setPageToken($optionalArgs['pageToken']);
        }

        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->getPagedListResponse('ListLocations', $optionalArgs, ListLocationsResponse::class, $request, 'google.cloud.location.Locations');
    }
}
