"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrderedDistinctEndpointComponent = void 0;
const hashObject_js_1 = require("../../utils/hashObject.js");
const parallelQueryResult_js_1 = require("../parallelQueryResult.js");
const PartitionRangeUtils_js_1 = require("../PartitionRangeUtils.js");
/** @hidden */
class OrderedDistinctEndpointComponent {
    executionContext;
    hashedLastResult;
    constructor(executionContext, hashedLastResult) {
        this.executionContext = executionContext;
        this.hashedLastResult = hashedLastResult;
    }
    hasMoreResults() {
        return this.executionContext.hasMoreResults();
    }
    async fetchMore(diagnosticNode) {
        const buffer = [];
        const response = await this.executionContext.fetchMore(diagnosticNode);
        if (!response ||
            !response.result ||
            !Array.isArray(response.result.buffer) ||
            response.result.buffer.length === 0) {
            return { result: response.result, headers: response.headers };
        }
        const parallelResult = response.result;
        const dataToProcess = parallelResult.buffer;
        const partitionKeyRangeMap = parallelResult.partitionKeyRangeMap;
        const updatedContinuationRanges = parallelResult.updatedContinuationRanges;
        const orderByItems = parallelResult.orderByItems;
        // Process each item and maintain hashedLastResult for distinct filtering
        for (const item of dataToProcess) {
            if (item) {
                const hashedResult = await (0, hashObject_js_1.hashObject)(item);
                if (hashedResult !== this.hashedLastResult) {
                    buffer.push(item);
                    this.hashedLastResult = hashedResult;
                }
            }
        }
        // Process distinct query logic and update partition key range map with hashedLastResult
        const updatedPartitionKeyRangeMap = await (0, PartitionRangeUtils_js_1.processDistinctQueryAndUpdateRangeMap)(dataToProcess, partitionKeyRangeMap, hashObject_js_1.hashObject);
        // Return in the new structure format using the utility function
        const result = (0, parallelQueryResult_js_1.createParallelQueryResult)(buffer, updatedPartitionKeyRangeMap, updatedContinuationRanges, orderByItems);
        return {
            result,
            headers: response.headers,
        };
    }
}
exports.OrderedDistinctEndpointComponent = OrderedDistinctEndpointComponent;
//# sourceMappingURL=OrderedDistinctEndpointComponent.js.map