import { describe, expect, it, jest } from '@jest/globals';
import { Pinger } from '../js/messenger.js';
import { wait, waitForEvent, isResolved, isSettled, isRejected, AbortError } from '../js/async/promise.js';

import '../js/ext/polyfills.js';
import './mocks/websocket.js';


describe('setInterval', () => {
    it ('returns a positive number', () => {
        const timer = setInterval(() => false, 1000);
        clearInterval(timer);
        expect(timer).toBeGreaterThan(0);
    })
})

describe('Pinger(interval)', () => {

    it ('initial interval is given in the contructor', () => {
        const pinger = new Pinger(27);
        expect(pinger.interval).toBe(27);
    })

    it ('.message is an object with the ping message', () => {
        const pinger = new Pinger();
        expect(pinger.message).toHaveProperty('type', 'ctl');
        expect(pinger.message).toHaveProperty('name', 'ping');
    })

    it ('start() activates and stop() deactivates the pinger', () => {
        const pinger = new Pinger();
        expect(pinger.active).toBeFalsy();
        pinger.start();
        expect(pinger.active).toBeTruthy();
        pinger.stop();
        expect(pinger.active).toBeFalsy();
    })

    it ('when active, message is send to all connections periodically', async () => {
        const pinger = new Pinger(1);
        const socket1 = new WebSocket('http://test.com/ws1');
        const socket2 = new WebSocket('http://test.com/ws2');

        pinger.connections.add(socket1);
        pinger.connections.add(socket2);

        WebSocket.controllers.get(socket1).open();
        WebSocket.controllers.get(socket2).open();

        pinger.start();
        await wait(1500);
        expect(socket1.send).toBeCalled();
        expect(socket2.send).toBeCalled();

        pinger.stop();
    })

})