// Wake detector - notices when something (such as
// suspension/sleeping!) has caused periodic activities to be
// interrupted, and warns others about it. Inspired by
// http://blog.alexmaccaw.com/javascript-wake-event

import { Ref, Turn, Observe } from "@syndicate-lang/core";

export message type WakeEvent();

export function boot(ds: Ref, period0?: number) {
    const period = period0 ?? 10000;
    at ds {
        during Observe({ "pattern": :pattern WakeEvent() }) => spawn named 'WakeDetector' {
            const facet = Turn.activeFacet;
            let mostRecentTrigger = +(new Date());
            const timerId = setInterval(() => facet.turn(() => {
                const now = +(new Date());
                if (now - mostRecentTrigger > period * 1.5) {
                    send message WakeEvent();
                }
                mostRecentTrigger = now;
            }), period);
            on stop clearInterval(timerId);
        }
    }
}
