export const Tokens = {
    channels: new Set(),
    controlers: new Set(),
    async list(token) {
        const url = "./example/token.php" + (token ? `?token=${token}` : '');
        const response = await fetch(url, { credentials: 'include' });
        return await response.text();
    },
    async generate(payload) {
        return await fetch('./example/token.php', {
            method: 'POST',
            headers: { 'Content-Type': 'text/json' },
            credentials: 'include',
            body: JSON.stringify(payload)
        }).then(res => res.text());
    },
    async channel({group, pub, sub} = {}) {
        const data = { group };
        if (pub) data.pub = Array.isArray(pub) ? pub.join(',') : pub;
        if (sub) data.sub = Array.isArray(sub) ? sub.join(',') : sub;
        const token = await this.generate(data);
        this.channels.add(token);
        return token;
    },
    async controller({ group, ctl } = {}) {
        const data = { group };
        if (Array.isArray(ctl)) {
            data.ctl = ctl.join(',');
        } else if (typeof ctl === 'string') {
            data.ctl = ctl;
        } else {
            data.ctl = '';
        }
        const token = await this.generate(data);
        this.controlers.add(token);
        return token;
    }
};
