"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.LegacyFetchImplementation = void 0;
const headerUtils_js_1 = require("./headerUtils.js");
/**
 * Legacy fetch implementation for when enableQueryControl is false
 * @hidden
 */
class LegacyFetchImplementation {
    endpoint;
    pageSize;
    constructor(endpoint, pageSize) {
        this.endpoint = endpoint;
        this.pageSize = pageSize;
    }
    async fetchMore(diagnosticNode, fetchBuffer) {
        // Initialize headers fresh for each fetchMore call
        const fetchMoreRespHeaders = (0, headerUtils_js_1.getInitialHeader)();
        try {
            // Keep fetching until we have enough items or no more results
            while (fetchBuffer.length < this.pageSize && this.endpoint.hasMoreResults()) {
                const response = await this.endpoint.fetchMore(diagnosticNode);
                (0, headerUtils_js_1.mergeHeaders)(fetchMoreRespHeaders, response.headers);
                if (!response ||
                    !response.result ||
                    !response.result.buffer ||
                    response.result.buffer.length === 0) {
                    if (fetchBuffer.length > 0) {
                        const copiedFetchBuffer = [...fetchBuffer];
                        fetchBuffer.length = 0; // Clear array in place
                        return { result: copiedFetchBuffer, headers: fetchMoreRespHeaders };
                    }
                    else {
                        return { result: undefined, headers: fetchMoreRespHeaders };
                    }
                }
                fetchBuffer.push(...response.result.buffer);
            }
            // Return collected items up to pageSize
            if (fetchBuffer.length > 0) {
                const temp = fetchBuffer.slice(0, this.pageSize);
                fetchBuffer.splice(0, this.pageSize); // Remove items in place
                return { result: temp, headers: fetchMoreRespHeaders };
            }
            else {
                return { result: undefined, headers: fetchMoreRespHeaders };
            }
        }
        catch (err) {
            (0, headerUtils_js_1.mergeHeaders)(fetchMoreRespHeaders, err.headers);
            err.headers = fetchMoreRespHeaders;
            throw err;
        }
    }
}
exports.LegacyFetchImplementation = LegacyFetchImplementation;
//# sourceMappingURL=LegacyFetchImplementation.js.map