export class PoitCloudSyncFramework {
    #binarySearch(arr, targetKey) {
        let left = 0;
        let right = arr.length;
        let bestMatch = null;
        const element = arr[arr.length - 1];
        if (!element) {
            return { res: null, index: 0 };
        }
        if (element.timestamp.nsec < targetKey) {
            return { res: arr[arr.length - 1], index: arr.length };
        }
        while (left <= right) {
            const mid = Math.floor((left + right) / 2);
            // biome-ignore lint/style/noNonNullAssertion:
            const midKey = arr[mid].timestamp.nsec;
            if (midKey === targetKey) {
                if ((Math.abs(midKey - targetKey) / 10 ** 9) < this.#MAX_DELAY_SEC) {
                    return { res: bestMatch, index: left };
                }
                return { res: null, index: mid };
            }
            if (midKey < targetKey) {
                bestMatch = arr[mid];
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }
        if (bestMatch && (Math.abs(bestMatch.timestamp.nsec - targetKey) / 10 ** 9) < this.#MAX_DELAY_SEC) {
            return { res: bestMatch, index: left };
        }
        return { res: null, index: left };
    }
    storedFrames = [];
    #MAX_DELAY_SEC = 0.065;
    #MAX_STORED_FRAMES = 100;
    getFrame(nsec) {
        const { res, index = 0 } = this.#binarySearch(this.storedFrames, nsec);
        // cleans the array
        for (let i = 0; i < index; i++) {
            Array.prototype.shift.call(this.storedFrames);
        }
        if (res) {
            return res;
        }
        const popedFrame = this.storedFrames.pop();
        if (popedFrame) {
            if ((Math.abs(popedFrame.timestamp.nsec - nsec) / 10 ** 9) < this.#MAX_DELAY_SEC) {
                return popedFrame;
            }
            //@ts-ignore
            this.storedFrames.push(popedFrame);
        }
        return null;
    }
    addFrame(frame) {
        if (Object.keys(this.storedFrames).length > this.#MAX_STORED_FRAMES) {
            return;
        }
        //@ts-ignore
        this.storedFrames.push(frame);
    }
}
//# sourceMappingURL=poitcloud-sync.js.map