;"use strict";

import * as Nchan from './js/medium/nchan.js';

import { Tokens, enhanceClass } from './controller.js';
import { Messenger, UrlFactory, ControllerUrlFactory } from './js/index.js';

// For testing
Object.assign(window, {
    Nchan,
    UrlFactory,
    ControllerUrlFactory,
    Messenger,
    Tokens,
    enhanceClass,
    async testnchan(hook, channel, token=false) {
        const ctl = new AbortController();
        const options = { signal: ctl.signal };
        if (token === true) {
            options.authorization = await Tokens.generate(token);
        } else if (typeof token === 'string') {
            options.authorization = token;
        }
        Nchan.publish(
            new URL(`./messenger/test/pub/${channel || 'ch3'}`, location.href),
            JSON.stringify({ type: 'message', name: 'console', payload: `test ${hook}` }),
            options
        ).then(
            () => console.log(`[Test ${hook}] OK`),
            err => console.error(`[Test ${hook}]`, err)
        );
    },
    async testws(url, name, tokenData=null) {
        if (tokenData) {
            if (!url.endsWith('/')) url += '/';
            url += await Tokens.generate(tokenData);
        }
        const ws = new WebSocket(url);
        ws.onopen = () => console.info(`[${name}] opened`);
        ws.onclose = evt => console.info(`[${name}] closed with code ${evt.code}`);
        ws.onerror = evt => console.error(`[${name}]`, evt);
        ws.onmessage = evt => console.info(`[${name}] message: `, evt.data);
        return ws;
    }
});
