import { passThrough } from "../../function/passThrough.js";
import Signal from "./Signal.js";

/**
 *
 * @param {number} delay in milliseconds
 * @param {function} [transform]
 * @param {*} [thisArg]
 * @returns {{handler: handler, signal: Signal}}
 */
export function signal_aggregate_by_time_window(delay, transform = passThrough, thisArg) {
    let bucket = [];
    let timeout = null;

    const signal = new Signal();

    function timeoutHandler() {
        timeout = null;

        signal.send1(bucket);

        //create a new bucket
        bucket = [];
    }

    function handler(arg) {
        if (timeout === null) {
            //create a timeout
            timeout = setTimeout(timeoutHandler, delay);
        }

        const item = transform.call(thisArg, arg);

        bucket.push(item);
    }

    return {
        signal,
        handler
    };
}
