<?php
/*
 * Copyright 2021 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/retail/v2/product_service.proto
 * Updates to the above are reflected here through a refresh process.
 */

namespace Google\Cloud\Retail\V2\Gapic;

use Google\ApiCore\ApiException;
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\Retail\V2\AddFulfillmentPlacesRequest;
use Google\Cloud\Retail\V2\AddLocalInventoriesRequest;
use Google\Cloud\Retail\V2\CreateProductRequest;
use Google\Cloud\Retail\V2\DeleteProductRequest;
use Google\Cloud\Retail\V2\GetProductRequest;
use Google\Cloud\Retail\V2\ImportErrorsConfig;
use Google\Cloud\Retail\V2\ImportProductsRequest;
use Google\Cloud\Retail\V2\ImportProductsRequest\ReconciliationMode;
use Google\Cloud\Retail\V2\ListProductsRequest;
use Google\Cloud\Retail\V2\ListProductsResponse;
use Google\Cloud\Retail\V2\LocalInventory;
use Google\Cloud\Retail\V2\Product;
use Google\Cloud\Retail\V2\ProductInputConfig;
use Google\Cloud\Retail\V2\RemoveFulfillmentPlacesRequest;
use Google\Cloud\Retail\V2\RemoveLocalInventoriesRequest;
use Google\Cloud\Retail\V2\SetInventoryRequest;
use Google\Cloud\Retail\V2\UpdateProductRequest;
use Google\LongRunning\Operation;
use Google\Protobuf\FieldMask;
use Google\Protobuf\GPBEmpty;
use Google\Protobuf\Timestamp;

/**
 * Service Description: Service for ingesting [Product][google.cloud.retail.v2.Product] information
 * of the customer's website.
 *
 * 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:
 *
 * ```
 * $productServiceClient = new ProductServiceClient();
 * try {
 *     $formattedProduct = $productServiceClient->productName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]', '[PRODUCT]');
 *     $type = 'type';
 *     $placeIds = [];
 *     $operationResponse = $productServiceClient->addFulfillmentPlaces($formattedProduct, $type, $placeIds);
 *     $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 = $productServiceClient->addFulfillmentPlaces($formattedProduct, $type, $placeIds);
 *     $operationName = $operationResponse->getName();
 *     // ... do other work
 *     $newOperationResponse = $productServiceClient->resumeOperation($operationName, 'addFulfillmentPlaces');
 *     while (!$newOperationResponse->isDone()) {
 *         // ... do other work
 *         $newOperationResponse->reload();
 *     }
 *     if ($newOperationResponse->operationSucceeded()) {
 *         $result = $newOperationResponse->getResult();
 *     // doSomethingWith($result)
 *     } else {
 *         $error = $newOperationResponse->getError();
 *         // handleError($error)
 *     }
 * } finally {
 *     $productServiceClient->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 ProductServiceGapicClient
{
    use GapicClientTrait;

    /** The name of the service. */
    const SERVICE_NAME = 'google.cloud.retail.v2.ProductService';

    /** The default address of the service. */
    const SERVICE_ADDRESS = 'retail.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',
    ];

    private static $branchNameTemplate;

    private static $productNameTemplate;

    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/product_service_client_config.json',
            'descriptorsConfigPath' =>
                __DIR__ . '/../resources/product_service_descriptor_config.php',
            'gcpApiConfigPath' =>
                __DIR__ . '/../resources/product_service_grpc_config.json',
            'credentialsConfig' => [
                'defaultScopes' => self::$serviceScopes,
            ],
            'transportConfig' => [
                'rest' => [
                    'restClientConfigPath' =>
                        __DIR__ .
                        '/../resources/product_service_rest_client_config.php',
                ],
            ],
        ];
    }

    private static function getBranchNameTemplate()
    {
        if (self::$branchNameTemplate == null) {
            self::$branchNameTemplate = new PathTemplate(
                'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}'
            );
        }

        return self::$branchNameTemplate;
    }

    private static function getProductNameTemplate()
    {
        if (self::$productNameTemplate == null) {
            self::$productNameTemplate = new PathTemplate(
                'projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}'
            );
        }

        return self::$productNameTemplate;
    }

    private static function getPathTemplateMap()
    {
        if (self::$pathTemplateMap == null) {
            self::$pathTemplateMap = [
                'branch' => self::getBranchNameTemplate(),
                'product' => self::getProductNameTemplate(),
            ];
        }

        return self::$pathTemplateMap;
    }

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

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

    /**
     * Parses a formatted name string and returns an associative array of the components in the name.
     * The following name formats are supported:
     * Template: Pattern
     * - branch: projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}
     * - product: projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}/products/{product}
     *
     * 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 'retail.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);
    }

    /**
     * Incrementally adds place IDs to
     * [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids].
     *
     * This process is asynchronous and does not require the
     * [Product][google.cloud.retail.v2.Product] to exist before updating
     * fulfillment information. If the request is valid, the update will be
     * enqueued and processed downstream. As a consequence, when a response is
     * returned, the added place IDs are not immediately manifested in the
     * [Product][google.cloud.retail.v2.Product] queried by
     * [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]
     * or
     * [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts].
     *
     * The returned [Operation][google.longrunning.Operation]s will be obsolete
     * after 1 day, and [GetOperation][google.longrunning.Operations.GetOperation]
     * API will return NOT_FOUND afterwards.
     *
     * If conflicting updates are issued, the
     * [Operation][google.longrunning.Operation]s associated with the stale
     * updates will not be marked as [done][google.longrunning.Operation.done]
     * until being obsolete.
     *
     * This feature is only available for users who have Retail Search enabled.
     * Enable Retail Search on Cloud Console before using this feature.
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedProduct = $productServiceClient->productName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]', '[PRODUCT]');
     *     $type = 'type';
     *     $placeIds = [];
     *     $operationResponse = $productServiceClient->addFulfillmentPlaces($formattedProduct, $type, $placeIds);
     *     $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 = $productServiceClient->addFulfillmentPlaces($formattedProduct, $type, $placeIds);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $productServiceClient->resumeOperation($operationName, 'addFulfillmentPlaces');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string   $product      Required. Full resource name of [Product][google.cloud.retail.v2.Product],
     *                               such as
     *                               `projects/&#42;/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
     *
     *                               If the caller does not have permission to access the
     *                               [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                               exists, a PERMISSION_DENIED error is returned.
     * @param string   $type         Required. The fulfillment type, including commonly used types (such as
     *                               pickup in store and same day delivery), and custom types.
     *
     *                               Supported values:
     *
     *                               * "pickup-in-store"
     *                               * "ship-to-store"
     *                               * "same-day-delivery"
     *                               * "next-day-delivery"
     *                               * "custom-type-1"
     *                               * "custom-type-2"
     *                               * "custom-type-3"
     *                               * "custom-type-4"
     *                               * "custom-type-5"
     *
     *                               If this field is set to an invalid value other than these, an
     *                               INVALID_ARGUMENT error is returned.
     *
     *                               This field directly corresponds to
     *                               [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type].
     * @param string[] $placeIds     Required. The IDs for this
     *                               [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type], such as
     *                               the store IDs for "pickup-in-store" or the region IDs for
     *                               "same-day-delivery" to be added for this
     *                               [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type]. Duplicate
     *                               IDs will be automatically ignored.
     *
     *                               At least 1 value is required, and a maximum of 2000 values are allowed.
     *                               Each value must be a string with a length limit of 10 characters, matching
     *                               the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an
     *                               INVALID_ARGUMENT error is returned.
     *
     *                               If the total number of place IDs exceeds 2000 for this
     *                               [type][google.cloud.retail.v2.AddFulfillmentPlacesRequest.type] after
     *                               adding, then the update will be rejected.
     * @param array    $optionalArgs {
     *     Optional.
     *
     *     @type Timestamp $addTime
     *           The time when the fulfillment updates are issued, used to prevent
     *           out-of-order updates on fulfillment information. If not provided, the
     *           internal system time will be used.
     *     @type bool $allowMissing
     *           If set to true, and the [Product][google.cloud.retail.v2.Product] is not
     *           found, the fulfillment information will still be processed and retained for
     *           at most 1 day and processed once the
     *           [Product][google.cloud.retail.v2.Product] is created. If set to false, a
     *           NOT_FOUND error is returned if the
     *           [Product][google.cloud.retail.v2.Product] is not found.
     *     @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 addFulfillmentPlaces(
        $product,
        $type,
        $placeIds,
        array $optionalArgs = []
    ) {
        $request = new AddFulfillmentPlacesRequest();
        $requestParamHeaders = [];
        $request->setProduct($product);
        $request->setType($type);
        $request->setPlaceIds($placeIds);
        $requestParamHeaders['product'] = $product;
        if (isset($optionalArgs['addTime'])) {
            $request->setAddTime($optionalArgs['addTime']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

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

    /**
     * Updates local inventory information for a
     * [Product][google.cloud.retail.v2.Product] at a list of places, while
     * respecting the last update timestamps of each inventory field.
     *
     * This process is asynchronous and does not require the
     * [Product][google.cloud.retail.v2.Product] to exist before updating
     * inventory information. If the request is valid, the update will be enqueued
     * and processed downstream. As a consequence, when a response is returned,
     * updates are not immediately manifested in the
     * [Product][google.cloud.retail.v2.Product] queried by
     * [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]
     * or
     * [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts].
     *
     * Local inventory information can only be modified using this method.
     * [ProductService.CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct]
     * and
     * [ProductService.UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct]
     * has no effect on local inventories.
     *
     * The returned [Operation][google.longrunning.Operation]s will be obsolete
     * after 1 day, and [GetOperation][google.longrunning.Operations.GetOperation]
     * API will return NOT_FOUND afterwards.
     *
     * If conflicting updates are issued, the
     * [Operation][google.longrunning.Operation]s associated with the stale
     * updates will not be marked as [done][google.longrunning.Operation.done]
     * until being obsolete.
     *
     * This feature is only available for users who have Retail Search enabled.
     * Enable Retail Search on Cloud Console before using this feature.
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedProduct = $productServiceClient->productName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]', '[PRODUCT]');
     *     $localInventories = [];
     *     $operationResponse = $productServiceClient->addLocalInventories($formattedProduct, $localInventories);
     *     $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 = $productServiceClient->addLocalInventories($formattedProduct, $localInventories);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $productServiceClient->resumeOperation($operationName, 'addLocalInventories');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string           $product          Required. Full resource name of [Product][google.cloud.retail.v2.Product],
     *                                           such as
     *                                           `projects/&#42;/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
     *
     *                                           If the caller does not have permission to access the
     *                                           [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                                           exists, a PERMISSION_DENIED error is returned.
     * @param LocalInventory[] $localInventories Required. A list of inventory information at difference places. Each place
     *                                           is identified by its place ID. At most 3000 inventories are allowed per
     *                                           request.
     * @param array            $optionalArgs     {
     *     Optional.
     *
     *     @type FieldMask $addMask
     *           Indicates which inventory fields in the provided list of
     *           [LocalInventory][google.cloud.retail.v2.LocalInventory] to update. The
     *           field is updated to the provided value.
     *
     *           If a field is set while the place does not have a previous local inventory,
     *           the local inventory at that store is created.
     *
     *           If a field is set while the value of that field is not provided, the
     *           original field value, if it exists, is deleted.
     *
     *           If the mask is not set or set with empty paths, all inventory fields will
     *           be updated.
     *
     *           If an unsupported or unknown field is provided, an INVALID_ARGUMENT error
     *           is returned and the entire update will be ignored.
     *     @type Timestamp $addTime
     *           The time when the inventory updates are issued. Used to prevent
     *           out-of-order updates on local inventory fields. If not provided, the
     *           internal system time will be used.
     *     @type bool $allowMissing
     *           If set to true, and the [Product][google.cloud.retail.v2.Product] is not
     *           found, the local inventory will still be processed and retained for at most
     *           1 day and processed once the [Product][google.cloud.retail.v2.Product] is
     *           created. If set to false, a NOT_FOUND error is returned if the
     *           [Product][google.cloud.retail.v2.Product] is not found.
     *     @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 addLocalInventories(
        $product,
        $localInventories,
        array $optionalArgs = []
    ) {
        $request = new AddLocalInventoriesRequest();
        $requestParamHeaders = [];
        $request->setProduct($product);
        $request->setLocalInventories($localInventories);
        $requestParamHeaders['product'] = $product;
        if (isset($optionalArgs['addMask'])) {
            $request->setAddMask($optionalArgs['addMask']);
        }

        if (isset($optionalArgs['addTime'])) {
            $request->setAddTime($optionalArgs['addTime']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

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

    /**
     * Creates a [Product][google.cloud.retail.v2.Product].
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedParent = $productServiceClient->branchName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]');
     *     $product = new Product();
     *     $productId = 'product_id';
     *     $response = $productServiceClient->createProduct($formattedParent, $product, $productId);
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string  $parent       Required. The parent catalog resource name, such as
     *                              `projects/&#42;/locations/global/catalogs/default_catalog/branches/default_branch`.
     * @param Product $product      Required. The [Product][google.cloud.retail.v2.Product] to create.
     * @param string  $productId    Required. The ID to use for the [Product][google.cloud.retail.v2.Product],
     *                              which will become the final component of the
     *                              [Product.name][google.cloud.retail.v2.Product.name].
     *
     *                              If the caller does not have permission to create the
     *                              [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                              exists, a PERMISSION_DENIED error is returned.
     *
     *                              This field must be unique among all
     *                              [Product][google.cloud.retail.v2.Product]s with the same
     *                              [parent][google.cloud.retail.v2.CreateProductRequest.parent]. Otherwise, an
     *                              ALREADY_EXISTS error is returned.
     *
     *                              This field must be a UTF-8 encoded string with a length limit of 128
     *                              characters. Otherwise, an INVALID_ARGUMENT error is returned.
     * @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.
     * }
     *
     * @return \Google\Cloud\Retail\V2\Product
     *
     * @throws ApiException if the remote call fails
     */
    public function createProduct(
        $parent,
        $product,
        $productId,
        array $optionalArgs = []
    ) {
        $request = new CreateProductRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $request->setProduct($product);
        $request->setProductId($productId);
        $requestParamHeaders['parent'] = $parent;
        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->startCall(
            'CreateProduct',
            Product::class,
            $optionalArgs,
            $request
        )->wait();
    }

    /**
     * Deletes a [Product][google.cloud.retail.v2.Product].
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedName = $productServiceClient->productName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]', '[PRODUCT]');
     *     $productServiceClient->deleteProduct($formattedName);
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string $name         Required. Full resource name of [Product][google.cloud.retail.v2.Product],
     *                             such as
     *                             `projects/&#42;/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
     *
     *                             If the caller does not have permission to delete the
     *                             [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                             exists, a PERMISSION_DENIED error is returned.
     *
     *                             If the [Product][google.cloud.retail.v2.Product] to delete does not exist,
     *                             a NOT_FOUND error is returned.
     *
     *                             The [Product][google.cloud.retail.v2.Product] to delete can neither be a
     *                             [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]
     *                             [Product][google.cloud.retail.v2.Product] member nor a
     *                             [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY]
     *                             [Product][google.cloud.retail.v2.Product] with more than one
     *                             [variants][google.cloud.retail.v2.Product.Type.VARIANT]. Otherwise, an
     *                             INVALID_ARGUMENT error is returned.
     *
     *                             All inventory information for the named
     *                             [Product][google.cloud.retail.v2.Product] will be deleted.
     * @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 deleteProduct($name, array $optionalArgs = [])
    {
        $request = new DeleteProductRequest();
        $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(
            'DeleteProduct',
            GPBEmpty::class,
            $optionalArgs,
            $request
        )->wait();
    }

    /**
     * Gets a [Product][google.cloud.retail.v2.Product].
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedName = $productServiceClient->productName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]', '[PRODUCT]');
     *     $response = $productServiceClient->getProduct($formattedName);
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string $name         Required. Full resource name of [Product][google.cloud.retail.v2.Product],
     *                             such as
     *                             `projects/&#42;/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
     *
     *                             If the caller does not have permission to access the
     *                             [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                             exists, a PERMISSION_DENIED error is returned.
     *
     *                             If the requested [Product][google.cloud.retail.v2.Product] does not exist,
     *                             a NOT_FOUND error is returned.
     * @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.
     * }
     *
     * @return \Google\Cloud\Retail\V2\Product
     *
     * @throws ApiException if the remote call fails
     */
    public function getProduct($name, array $optionalArgs = [])
    {
        $request = new GetProductRequest();
        $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(
            'GetProduct',
            Product::class,
            $optionalArgs,
            $request
        )->wait();
    }

    /**
     * Bulk import of multiple [Product][google.cloud.retail.v2.Product]s.
     *
     * Request processing may be synchronous.
     * Non-existing items are created.
     *
     * Note that it is possible for a subset of the
     * [Product][google.cloud.retail.v2.Product]s to be successfully updated.
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedParent = $productServiceClient->branchName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]');
     *     $inputConfig = new ProductInputConfig();
     *     $operationResponse = $productServiceClient->importProducts($formattedParent, $inputConfig);
     *     $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 = $productServiceClient->importProducts($formattedParent, $inputConfig);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $productServiceClient->resumeOperation($operationName, 'importProducts');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string             $parent       Required.
     *                                         `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch`
     *
     *                                         If no updateMask is specified, requires products.create permission.
     *                                         If updateMask is specified, requires products.update permission.
     * @param ProductInputConfig $inputConfig  Required. The desired input location of the data.
     * @param array              $optionalArgs {
     *     Optional.
     *
     *     @type string $requestId
     *           Deprecated. This field has no effect.
     *     @type ImportErrorsConfig $errorsConfig
     *           The desired location of errors incurred during the Import.
     *     @type FieldMask $updateMask
     *           Indicates which fields in the provided imported `products` to update. If
     *           not set, all fields are updated.
     *     @type int $reconciliationMode
     *           The mode of reconciliation between existing products and the products to be
     *           imported. Defaults to
     *           [ReconciliationMode.INCREMENTAL][google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode.INCREMENTAL].
     *           For allowed values, use constants defined on {@see \Google\Cloud\Retail\V2\ImportProductsRequest\ReconciliationMode}
     *     @type string $notificationPubsubTopic
     *           Full Pub/Sub topic name for receiving notification. If this field is set,
     *           when the import is finished, a notification is sent to
     *           specified Pub/Sub topic. The message data is JSON string of a
     *           [Operation][google.longrunning.Operation].
     *
     *           Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`. It has
     *           to be within the same project as
     *           [ImportProductsRequest.parent][google.cloud.retail.v2.ImportProductsRequest.parent].
     *           Make sure that `service-<project
     *           number>&#64;gcp-sa-retail.iam.gserviceaccount.com` has the
     *           `pubsub.topics.publish` IAM permission on the topic.
     *     @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 importProducts(
        $parent,
        $inputConfig,
        array $optionalArgs = []
    ) {
        $request = new ImportProductsRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $request->setInputConfig($inputConfig);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['requestId'])) {
            $request->setRequestId($optionalArgs['requestId']);
        }

        if (isset($optionalArgs['errorsConfig'])) {
            $request->setErrorsConfig($optionalArgs['errorsConfig']);
        }

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

        if (isset($optionalArgs['reconciliationMode'])) {
            $request->setReconciliationMode(
                $optionalArgs['reconciliationMode']
            );
        }

        if (isset($optionalArgs['notificationPubsubTopic'])) {
            $request->setNotificationPubsubTopic(
                $optionalArgs['notificationPubsubTopic']
            );
        }

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

    /**
     * Gets a list of [Product][google.cloud.retail.v2.Product]s.
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedParent = $productServiceClient->branchName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]');
     *     // Iterate over pages of elements
     *     $pagedResponse = $productServiceClient->listProducts($formattedParent);
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $productServiceClient->listProducts($formattedParent);
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The parent branch resource name, such as
     *                             `projects/&#42;/locations/global/catalogs/default_catalog/branches/0`. Use
     *                             `default_branch` as the branch ID, to list products under the default
     *                             branch.
     *
     *                             If the caller does not have permission to list
     *                             [Product][google.cloud.retail.v2.Product]s under this branch, regardless of
     *                             whether or not this branch exists, a PERMISSION_DENIED error is returned.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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 string $filter
     *           A filter to apply on the list results. Supported features:
     *
     *           * List all the products under the parent branch if
     *           [filter][google.cloud.retail.v2.ListProductsRequest.filter] is unset.
     *           * List [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT]
     *           [Product][google.cloud.retail.v2.Product]s sharing the same
     *           [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY]
     *           [Product][google.cloud.retail.v2.Product]. For example:
     *           `primary_product_id = "some_product_id"`
     *           * List [Product][google.cloud.retail.v2.Product]s bundled in a
     *           [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]
     *           [Product][google.cloud.retail.v2.Product].
     *           For example:
     *           `collection_product_id = "some_product_id"`
     *           * List [Product][google.cloud.retail.v2.Product]s with a partibular type.
     *           For example:
     *           `type = "PRIMARY"`
     *           `type = "VARIANT"`
     *           `type = "COLLECTION"`
     *
     *           If the field is unrecognizable, an INVALID_ARGUMENT error is returned.
     *
     *           If the specified
     *           [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY]
     *           [Product][google.cloud.retail.v2.Product] or
     *           [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION]
     *           [Product][google.cloud.retail.v2.Product] does not exist, a NOT_FOUND error
     *           is returned.
     *     @type FieldMask $readMask
     *           The fields of [Product][google.cloud.retail.v2.Product] to return in the
     *           responses. If not set or empty, the following fields are returned:
     *
     *           * [Product.name][google.cloud.retail.v2.Product.name]
     *           * [Product.id][google.cloud.retail.v2.Product.id]
     *           * [Product.title][google.cloud.retail.v2.Product.title]
     *           * [Product.uri][google.cloud.retail.v2.Product.uri]
     *           * [Product.images][google.cloud.retail.v2.Product.images]
     *           * [Product.price_info][google.cloud.retail.v2.Product.price_info]
     *           * [Product.brands][google.cloud.retail.v2.Product.brands]
     *
     *           If "*" is provided, all fields are returned.
     *           [Product.name][google.cloud.retail.v2.Product.name] is always returned no
     *           matter what mask is set.
     *
     *           If an unsupported or unknown field is provided, an INVALID_ARGUMENT error
     *           is returned.
     *     @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 listProducts($parent, array $optionalArgs = [])
    {
        $request = new ListProductsRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

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

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

        if (isset($optionalArgs['readMask'])) {
            $request->setReadMask($optionalArgs['readMask']);
        }

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

    /**
     * Incrementally removes place IDs from a
     * [Product.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids].
     *
     * This process is asynchronous and does not require the
     * [Product][google.cloud.retail.v2.Product] to exist before updating
     * fulfillment information. If the request is valid, the update will be
     * enqueued and processed downstream. As a consequence, when a response is
     * returned, the removed place IDs are not immediately manifested in the
     * [Product][google.cloud.retail.v2.Product] queried by
     * [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]
     * or
     * [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts].
     *
     * The returned [Operation][google.longrunning.Operation]s will be obsolete
     * after 1 day, and [GetOperation][google.longrunning.Operations.GetOperation]
     * API will return NOT_FOUND afterwards.
     *
     * If conflicting updates are issued, the
     * [Operation][google.longrunning.Operation]s associated with the stale
     * updates will not be marked as [done][google.longrunning.Operation.done]
     * until being obsolete.
     *
     * This feature is only available for users who have Retail Search enabled.
     * Enable Retail Search on Cloud Console before using this feature.
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedProduct = $productServiceClient->productName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]', '[PRODUCT]');
     *     $type = 'type';
     *     $placeIds = [];
     *     $operationResponse = $productServiceClient->removeFulfillmentPlaces($formattedProduct, $type, $placeIds);
     *     $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 = $productServiceClient->removeFulfillmentPlaces($formattedProduct, $type, $placeIds);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $productServiceClient->resumeOperation($operationName, 'removeFulfillmentPlaces');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string   $product      Required. Full resource name of [Product][google.cloud.retail.v2.Product],
     *                               such as
     *                               `projects/&#42;/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
     *
     *                               If the caller does not have permission to access the
     *                               [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                               exists, a PERMISSION_DENIED error is returned.
     * @param string   $type         Required. The fulfillment type, including commonly used types (such as
     *                               pickup in store and same day delivery), and custom types.
     *
     *                               Supported values:
     *
     *                               * "pickup-in-store"
     *                               * "ship-to-store"
     *                               * "same-day-delivery"
     *                               * "next-day-delivery"
     *                               * "custom-type-1"
     *                               * "custom-type-2"
     *                               * "custom-type-3"
     *                               * "custom-type-4"
     *                               * "custom-type-5"
     *
     *                               If this field is set to an invalid value other than these, an
     *                               INVALID_ARGUMENT error is returned.
     *
     *                               This field directly corresponds to
     *                               [Product.fulfillment_info.type][google.cloud.retail.v2.FulfillmentInfo.type].
     * @param string[] $placeIds     Required. The IDs for this
     *                               [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type], such as
     *                               the store IDs for "pickup-in-store" or the region IDs for
     *                               "same-day-delivery", to be removed for this
     *                               [type][google.cloud.retail.v2.RemoveFulfillmentPlacesRequest.type].
     *
     *                               At least 1 value is required, and a maximum of 2000 values are allowed.
     *                               Each value must be a string with a length limit of 10 characters, matching
     *                               the pattern `[a-zA-Z0-9_-]+`, such as "store1" or "REGION-2". Otherwise, an
     *                               INVALID_ARGUMENT error is returned.
     * @param array    $optionalArgs {
     *     Optional.
     *
     *     @type Timestamp $removeTime
     *           The time when the fulfillment updates are issued, used to prevent
     *           out-of-order updates on fulfillment information. If not provided, the
     *           internal system time will be used.
     *     @type bool $allowMissing
     *           If set to true, and the [Product][google.cloud.retail.v2.Product] is not
     *           found, the fulfillment information will still be processed and retained for
     *           at most 1 day and processed once the
     *           [Product][google.cloud.retail.v2.Product] is created. If set to false, a
     *           NOT_FOUND error is returned if the
     *           [Product][google.cloud.retail.v2.Product] is not found.
     *     @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 removeFulfillmentPlaces(
        $product,
        $type,
        $placeIds,
        array $optionalArgs = []
    ) {
        $request = new RemoveFulfillmentPlacesRequest();
        $requestParamHeaders = [];
        $request->setProduct($product);
        $request->setType($type);
        $request->setPlaceIds($placeIds);
        $requestParamHeaders['product'] = $product;
        if (isset($optionalArgs['removeTime'])) {
            $request->setRemoveTime($optionalArgs['removeTime']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

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

    /**
     * Remove local inventory information for a
     * [Product][google.cloud.retail.v2.Product] at a list of places at a removal
     * timestamp.
     *
     * This process is asynchronous. If the request is valid, the removal will be
     * enqueued and processed downstream. As a consequence, when a response is
     * returned, removals are not immediately manifested in the
     * [Product][google.cloud.retail.v2.Product] queried by
     * [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]
     * or
     * [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts].
     *
     * Local inventory information can only be removed using this method.
     * [ProductService.CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct]
     * and
     * [ProductService.UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct]
     * has no effect on local inventories.
     *
     * The returned [Operation][google.longrunning.Operation]s will be obsolete
     * after 1 day, and [GetOperation][google.longrunning.Operations.GetOperation]
     * API will return NOT_FOUND afterwards.
     *
     * If conflicting updates are issued, the
     * [Operation][google.longrunning.Operation]s associated with the stale
     * updates will not be marked as [done][google.longrunning.Operation.done]
     * until being obsolete.
     *
     * This feature is only available for users who have Retail Search enabled.
     * Enable Retail Search on Cloud Console before using this feature.
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $formattedProduct = $productServiceClient->productName('[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]', '[PRODUCT]');
     *     $placeIds = [];
     *     $operationResponse = $productServiceClient->removeLocalInventories($formattedProduct, $placeIds);
     *     $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 = $productServiceClient->removeLocalInventories($formattedProduct, $placeIds);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $productServiceClient->resumeOperation($operationName, 'removeLocalInventories');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param string   $product      Required. Full resource name of [Product][google.cloud.retail.v2.Product],
     *                               such as
     *                               `projects/&#42;/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id`.
     *
     *                               If the caller does not have permission to access the
     *                               [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                               exists, a PERMISSION_DENIED error is returned.
     * @param string[] $placeIds     Required. A list of place IDs to have their inventory deleted.
     *                               At most 3000 place IDs are allowed per request.
     * @param array    $optionalArgs {
     *     Optional.
     *
     *     @type Timestamp $removeTime
     *           The time when the inventory deletions are issued. Used to prevent
     *           out-of-order updates and deletions on local inventory fields. If not
     *           provided, the internal system time will be used.
     *     @type bool $allowMissing
     *           If set to true, and the [Product][google.cloud.retail.v2.Product] is not
     *           found, the local inventory removal request will still be processed and
     *           retained for at most 1 day and processed once the
     *           [Product][google.cloud.retail.v2.Product] is created. If set to false, a
     *           NOT_FOUND error is returned if the
     *           [Product][google.cloud.retail.v2.Product] is not found.
     *     @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 removeLocalInventories(
        $product,
        $placeIds,
        array $optionalArgs = []
    ) {
        $request = new RemoveLocalInventoriesRequest();
        $requestParamHeaders = [];
        $request->setProduct($product);
        $request->setPlaceIds($placeIds);
        $requestParamHeaders['product'] = $product;
        if (isset($optionalArgs['removeTime'])) {
            $request->setRemoveTime($optionalArgs['removeTime']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

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

    /**
     * Updates inventory information for a
     * [Product][google.cloud.retail.v2.Product] while respecting the last update
     * timestamps of each inventory field.
     *
     * This process is asynchronous and does not require the
     * [Product][google.cloud.retail.v2.Product] to exist before updating
     * fulfillment information. If the request is valid, the update is enqueued
     * and processed downstream. As a consequence, when a response is returned,
     * updates are not immediately manifested in the
     * [Product][google.cloud.retail.v2.Product] queried by
     * [ProductService.GetProduct][google.cloud.retail.v2.ProductService.GetProduct]
     * or
     * [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts].
     *
     * When inventory is updated with
     * [ProductService.CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct]
     * and
     * [ProductService.UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct],
     * the specified inventory field value(s) overwrite any existing value(s)
     * while ignoring the last update time for this field. Furthermore, the last
     * update times for the specified inventory fields are overwritten by the
     * times of the
     * [ProductService.CreateProduct][google.cloud.retail.v2.ProductService.CreateProduct]
     * or
     * [ProductService.UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct]
     * request.
     *
     * If no inventory fields are set in
     * [CreateProductRequest.product][google.cloud.retail.v2.CreateProductRequest.product],
     * then any pre-existing inventory information for this product is used.
     *
     * If no inventory fields are set in
     * [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask],
     * then any existing inventory information is preserved.
     *
     * Pre-existing inventory information can only be updated with
     * [ProductService.SetInventory][google.cloud.retail.v2.ProductService.SetInventory],
     * [ProductService.AddFulfillmentPlaces][google.cloud.retail.v2.ProductService.AddFulfillmentPlaces],
     * and
     * [ProductService.RemoveFulfillmentPlaces][google.cloud.retail.v2.ProductService.RemoveFulfillmentPlaces].
     *
     * The returned [Operation][google.longrunning.Operation]s is obsolete after
     * one day, and the [GetOperation][google.longrunning.Operations.GetOperation]
     * API returns `NOT_FOUND` afterwards.
     *
     * If conflicting updates are issued, the
     * [Operation][google.longrunning.Operation]s associated with the stale
     * updates are not marked as [done][google.longrunning.Operation.done] until
     * they are obsolete.
     *
     * This feature is only available for users who have Retail Search enabled.
     * Enable Retail Search on Cloud Console before using this feature.
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $inventory = new Product();
     *     $operationResponse = $productServiceClient->setInventory($inventory);
     *     $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 = $productServiceClient->setInventory($inventory);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $productServiceClient->resumeOperation($operationName, 'setInventory');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param Product $inventory    Required. The inventory information to update. The allowable fields to
     *                              update are:
     *
     *                              * [Product.price_info][google.cloud.retail.v2.Product.price_info]
     *                              * [Product.availability][google.cloud.retail.v2.Product.availability]
     *                              * [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity]
     *                              * [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info]
     *                              The updated inventory fields must be specified in
     *                              [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask].
     *
     *                              If
     *                              [SetInventoryRequest.inventory.name][google.cloud.retail.v2.Product.name]
     *                              is empty or invalid, an INVALID_ARGUMENT error is returned.
     *
     *                              If the caller does not have permission to update the
     *                              [Product][google.cloud.retail.v2.Product] named in
     *                              [Product.name][google.cloud.retail.v2.Product.name], regardless of whether
     *                              or not it exists, a PERMISSION_DENIED error is returned.
     *
     *                              If the [Product][google.cloud.retail.v2.Product] to update does not have
     *                              existing inventory information, the provided inventory information will be
     *                              inserted.
     *
     *                              If the [Product][google.cloud.retail.v2.Product] to update has existing
     *                              inventory information, the provided inventory information will be merged
     *                              while respecting the last update time for each inventory field, using the
     *                              provided or default value for
     *                              [SetInventoryRequest.set_time][google.cloud.retail.v2.SetInventoryRequest.set_time].
     *
     *                              The caller can replace place IDs for a subset of fulfillment types in the
     *                              following ways:
     *
     *                              * Adds "fulfillment_info" in
     *                              [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]
     *                              * Specifies only the desired fulfillment types and corresponding place IDs
     *                              to update in
     *                              [SetInventoryRequest.inventory.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info]
     *
     *                              The caller can clear all place IDs from a subset of fulfillment types in
     *                              the following ways:
     *
     *                              * Adds "fulfillment_info" in
     *                              [SetInventoryRequest.set_mask][google.cloud.retail.v2.SetInventoryRequest.set_mask]
     *                              * Specifies only the desired fulfillment types to clear in
     *                              [SetInventoryRequest.inventory.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info]
     *                              * Checks that only the desired fulfillment info types have empty
     *                              [SetInventoryRequest.inventory.fulfillment_info.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids]
     *
     *                              The last update time is recorded for the following inventory fields:
     *                              * [Product.price_info][google.cloud.retail.v2.Product.price_info]
     *                              * [Product.availability][google.cloud.retail.v2.Product.availability]
     *                              * [Product.available_quantity][google.cloud.retail.v2.Product.available_quantity]
     *                              * [Product.fulfillment_info][google.cloud.retail.v2.Product.fulfillment_info]
     *
     *                              If a full overwrite of inventory information while ignoring timestamps is
     *                              needed,
     *                              [ProductService.UpdateProduct][google.cloud.retail.v2.ProductService.UpdateProduct]
     *                              should be invoked instead.
     * @param array   $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $setMask
     *           Indicates which inventory fields in the provided
     *           [Product][google.cloud.retail.v2.Product] to update.
     *
     *           At least one field must be provided.
     *
     *           If an unsupported or unknown field is provided, an INVALID_ARGUMENT error
     *           is returned and the entire update will be ignored.
     *     @type Timestamp $setTime
     *           The time when the request is issued, used to prevent
     *           out-of-order updates on inventory fields with the last update time
     *           recorded. If not provided, the internal system time will be used.
     *     @type bool $allowMissing
     *           If set to true, and the [Product][google.cloud.retail.v2.Product] with name
     *           [Product.name][google.cloud.retail.v2.Product.name] is not found, the
     *           inventory update will still be processed and retained for at most 1 day
     *           until the [Product][google.cloud.retail.v2.Product] is created. If set to
     *           false, a NOT_FOUND error is returned if the
     *           [Product][google.cloud.retail.v2.Product] is not found.
     *     @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 setInventory($inventory, array $optionalArgs = [])
    {
        $request = new SetInventoryRequest();
        $requestParamHeaders = [];
        $request->setInventory($inventory);
        $requestParamHeaders['inventory.name'] = $inventory->getName();
        if (isset($optionalArgs['setMask'])) {
            $request->setSetMask($optionalArgs['setMask']);
        }

        if (isset($optionalArgs['setTime'])) {
            $request->setSetTime($optionalArgs['setTime']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

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

    /**
     * Updates a [Product][google.cloud.retail.v2.Product].
     *
     * Sample code:
     * ```
     * $productServiceClient = new ProductServiceClient();
     * try {
     *     $product = new Product();
     *     $response = $productServiceClient->updateProduct($product);
     * } finally {
     *     $productServiceClient->close();
     * }
     * ```
     *
     * @param Product $product      Required. The product to update/create.
     *
     *                              If the caller does not have permission to update the
     *                              [Product][google.cloud.retail.v2.Product], regardless of whether or not it
     *                              exists, a PERMISSION_DENIED error is returned.
     *
     *                              If the [Product][google.cloud.retail.v2.Product] to update does not exist
     *                              and
     *                              [allow_missing][google.cloud.retail.v2.UpdateProductRequest.allow_missing]
     *                              is not set, a NOT_FOUND error is returned.
     * @param array   $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $updateMask
     *           Indicates which fields in the provided
     *           [Product][google.cloud.retail.v2.Product] to update. The immutable and
     *           output only fields are NOT supported. If not set, all supported fields (the
     *           fields that are neither immutable nor output only) are updated.
     *
     *           If an unsupported or unknown field is provided, an INVALID_ARGUMENT error
     *           is returned.
     *
     *           The attribute key can be updated by setting the mask path as
     *           "attributes.${key_name}". If a key name is present in the mask but not in
     *           the patching product from the request, this key will be deleted after the
     *           update.
     *     @type bool $allowMissing
     *           If set to true, and the [Product][google.cloud.retail.v2.Product] is not
     *           found, a new [Product][google.cloud.retail.v2.Product] will be created. In
     *           this situation, `update_mask` is ignored.
     *     @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\Retail\V2\Product
     *
     * @throws ApiException if the remote call fails
     */
    public function updateProduct($product, array $optionalArgs = [])
    {
        $request = new UpdateProductRequest();
        $requestParamHeaders = [];
        $request->setProduct($product);
        $requestParamHeaders['product.name'] = $product->getName();
        if (isset($optionalArgs['updateMask'])) {
            $request->setUpdateMask($optionalArgs['updateMask']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

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