"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlobBatchClient = void 0;
const BatchResponseParser_js_1 = require("./BatchResponseParser.js");
const BatchUtils_js_1 = require("./BatchUtils.js");
const BlobBatch_js_1 = require("./BlobBatch.js");
const tracing_js_1 = require("./utils/tracing.js");
const storage_common_1 = require("@azure/storage-common");
const StorageContextClient_js_1 = require("./StorageContextClient.js");
const Pipeline_js_1 = require("./Pipeline.js");
const utils_common_js_1 = require("./utils/utils.common.js");
/**
 * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service.
 *
 * @see https://learn.microsoft.com/rest/api/storageservices/blob-batch
 */
class BlobBatchClient {
    serviceOrContainerContext;
    constructor(url, credentialOrPipeline, 
    // Legacy, no fix for eslint error without breaking. Disable it for this interface.
    /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/
    options) {
        let pipeline;
        if ((0, Pipeline_js_1.isPipelineLike)(credentialOrPipeline)) {
            pipeline = credentialOrPipeline;
        }
        else if (!credentialOrPipeline) {
            // no credential provided
            pipeline = (0, Pipeline_js_1.newPipeline)(new storage_common_1.AnonymousCredential(), options);
        }
        else {
            pipeline = (0, Pipeline_js_1.newPipeline)(credentialOrPipeline, options);
        }
        const storageClientContext = new StorageContextClient_js_1.StorageContextClient(url, (0, Pipeline_js_1.getCoreClientOptions)(pipeline));
        const path = (0, utils_common_js_1.getURLPath)(url);
        if (path && path !== "/") {
            // Container scoped.
            this.serviceOrContainerContext = storageClientContext.container;
        }
        else {
            this.serviceOrContainerContext = storageClientContext.service;
        }
    }
    /**
     * Creates a {@link BlobBatch}.
     * A BlobBatch represents an aggregated set of operations on blobs.
     */
    createBatch() {
        return new BlobBatch_js_1.BlobBatch();
    }
    async deleteBlobs(urlsOrBlobClients, credentialOrOptions, 
    // Legacy, no fix for eslint error without breaking. Disable it for this interface.
    /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/
    options) {
        const batch = new BlobBatch_js_1.BlobBatch();
        for (const urlOrBlobClient of urlsOrBlobClients) {
            if (typeof urlOrBlobClient === "string") {
                await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options);
            }
            else {
                await batch.deleteBlob(urlOrBlobClient, credentialOrOptions);
            }
        }
        return this.submitBatch(batch);
    }
    async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, 
    // Legacy, no fix for eslint error without breaking. Disable it for this interface.
    /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/
    options) {
        const batch = new BlobBatch_js_1.BlobBatch();
        for (const urlOrBlobClient of urlsOrBlobClients) {
            if (typeof urlOrBlobClient === "string") {
                await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options);
            }
            else {
                await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions);
            }
        }
        return this.submitBatch(batch);
    }
    /**
     * Submit batch request which consists of multiple subrequests.
     *
     * Get `blobBatchClient` and other details before running the snippets.
     * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient`
     *
     * Example usage:
     *
     * ```ts snippet:BlobBatchClientSubmitBatch
     * import { DefaultAzureCredential } from "@azure/identity";
     * import { BlobServiceClient, BlobBatch } from "@azure/storage-blob";
     *
     * const account = "<account>";
     * const credential = new DefaultAzureCredential();
     * const blobServiceClient = new BlobServiceClient(
     *   `https://${account}.blob.core.windows.net`,
     *   credential,
     * );
     *
     * const containerName = "<container name>";
     * const containerClient = blobServiceClient.getContainerClient(containerName);
     * const blobBatchClient = containerClient.getBlobBatchClient();
     *
     * const batchRequest = new BlobBatch();
     * await batchRequest.deleteBlob("<blob-url-1>", credential);
     * await batchRequest.deleteBlob("<blob-url-2>", credential, {
     *   deleteSnapshots: "include",
     * });
     * const batchResp = await blobBatchClient.submitBatch(batchRequest);
     * console.log(batchResp.subResponsesSucceededCount);
     * ```
     *
     * Example using a lease:
     *
     * ```ts snippet:BlobBatchClientSubmitBatchWithLease
     * import { DefaultAzureCredential } from "@azure/identity";
     * import { BlobServiceClient, BlobBatch } from "@azure/storage-blob";
     *
     * const account = "<account>";
     * const credential = new DefaultAzureCredential();
     * const blobServiceClient = new BlobServiceClient(
     *   `https://${account}.blob.core.windows.net`,
     *   credential,
     * );
     *
     * const containerName = "<container name>";
     * const containerClient = blobServiceClient.getContainerClient(containerName);
     * const blobBatchClient = containerClient.getBlobBatchClient();
     * const blobClient = containerClient.getBlobClient("<blob name>");
     *
     * const batchRequest = new BlobBatch();
     * await batchRequest.setBlobAccessTier(blobClient, "Cool");
     * await batchRequest.setBlobAccessTier(blobClient, "Cool", {
     *   conditions: { leaseId: "<lease-id>" },
     * });
     * const batchResp = await blobBatchClient.submitBatch(batchRequest);
     * console.log(batchResp.subResponsesSucceededCount);
     * ```
     *
     * @see https://learn.microsoft.com/rest/api/storageservices/blob-batch
     *
     * @param batchRequest - A set of Delete or SetTier operations.
     * @param options -
     */
    async submitBatch(batchRequest, options = {}) {
        if (!batchRequest || batchRequest.getSubRequests().size === 0) {
            throw new RangeError("Batch request should contain one or more sub requests.");
        }
        return tracing_js_1.tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => {
            const batchRequestBody = batchRequest.getHttpRequestBody();
            // ServiceSubmitBatchResponseModel and ContainerSubmitBatchResponse are compatible for now.
            const rawBatchResponse = (0, utils_common_js_1.assertResponse)((await this.serviceOrContainerContext.submitBatch((0, BatchUtils_js_1.utf8ByteLength)(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, {
                ...updatedOptions,
            })));
            // Parse the sub responses result, if logic reaches here(i.e. the batch request succeeded with status code 202).
            const batchResponseParser = new BatchResponseParser_js_1.BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests());
            const responseSummary = await batchResponseParser.parseBatchResponse();
            const res = {
                _response: rawBatchResponse._response,
                contentType: rawBatchResponse.contentType,
                errorCode: rawBatchResponse.errorCode,
                requestId: rawBatchResponse.requestId,
                clientRequestId: rawBatchResponse.clientRequestId,
                version: rawBatchResponse.version,
                subResponses: responseSummary.subResponses,
                subResponsesSucceededCount: responseSummary.subResponsesSucceededCount,
                subResponsesFailedCount: responseSummary.subResponsesFailedCount,
            };
            return res;
        });
    }
}
exports.BlobBatchClient = BlobBatchClient;
//# sourceMappingURL=BlobBatchClient.js.map