"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrderByEndpointComponent = void 0;
const parallelQueryResult_js_1 = require("../parallelQueryResult.js");
/** @hidden */
class OrderByEndpointComponent {
    executionContext;
    emitRawOrderByPayload;
    /**
     * Represents an endpoint in handling an order by query. For each processed orderby
     * result it returns 'payload' item of the result
     *
     * @param executionContext - Underlying Execution Context
     * @param emitRawOrderByPayload - Whether to emit raw order by payload
     * @hidden
     */
    constructor(executionContext, emitRawOrderByPayload = false) {
        this.executionContext = executionContext;
        this.emitRawOrderByPayload = emitRawOrderByPayload;
    }
    /**
     * Determine if there are still remaining resources to processs.
     * @returns true if there is other elements to process in the OrderByEndpointComponent.
     */
    hasMoreResults() {
        return this.executionContext.hasMoreResults();
    }
    async fetchMore(diagnosticNode) {
        const buffer = [];
        const orderByItemsArray = []; // Store order by items for each item
        const response = await this.executionContext.fetchMore(diagnosticNode);
        if (!response ||
            !response.result ||
            !Array.isArray(response.result.buffer) ||
            response.result.buffer.length === 0) {
            // Preserve the partitionKeyRangeMap and updatedContinuationRanges from the original response
            // even when the buffer is empty, as they contain continuation token information
            const originalResult = response?.result;
            const result = (0, parallelQueryResult_js_1.createParallelQueryResult)([], originalResult?.partitionKeyRangeMap || new Map(), originalResult?.updatedContinuationRanges || {}, []);
            return { result, headers: response?.headers };
        }
        const parallelResult = response.result;
        const rawBuffer = parallelResult.buffer;
        const partitionKeyRangeMap = parallelResult.partitionKeyRangeMap;
        const updatedContinuationRanges = parallelResult.updatedContinuationRanges;
        // Process buffer items and collect order by items for each item
        for (let i = 0; i < rawBuffer.length; i++) {
            const item = rawBuffer[i];
            if (this.emitRawOrderByPayload) {
                buffer.push(item);
            }
            else {
                buffer.push(item.payload);
            }
            orderByItemsArray.push({ orderByItems: item.orderByItems, _rid: item._rid });
        }
        const result = (0, parallelQueryResult_js_1.createParallelQueryResult)(buffer, partitionKeyRangeMap, updatedContinuationRanges, orderByItemsArray);
        return { result, headers: response.headers };
    }
}
exports.OrderByEndpointComponent = OrderByEndpointComponent;
//# sourceMappingURL=OrderByEndpointComponent.js.map