"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.openReceiverChannel = openReceiverChannel;
exports.openTransmitterChannel = openTransmitterChannel;
exports.listenChannel = listenChannel;
exports.postMessage = postMessage;
const EventEmitter_1 = require("../EventEmitter");
const _transmitterChannel = {};
const _receiverChannel = {};
const _eventEmitter = new EventEmitter_1.EventEmitter_();
function openReceiverChannel(channel) {
    let receiverChannel = _receiverChannel[channel];
    if (!receiverChannel) {
        receiverChannel = new BroadcastChannel(channel);
        receiverChannel.onmessage = function (message) {
            const { data } = message;
            _eventEmitter.emit(channel, data);
        };
        receiverChannel.onmessageerror = function (messageerror) {
            // console.log('messageerror', messageerror)
        };
        _receiverChannel[channel] = receiverChannel;
    }
    return receiverChannel;
}
function openTransmitterChannel(channel) {
    let transmitterChannel = _transmitterChannel[channel];
    if (!transmitterChannel) {
        transmitterChannel = new BroadcastChannel(channel);
        _transmitterChannel[channel] = transmitterChannel;
    }
    return transmitterChannel;
}
function listenChannel(channel, listener) {
    openReceiverChannel(channel);
    _eventEmitter.addListener(channel, listener);
    return () => {
        _eventEmitter.removeListener(channel, listener);
    };
}
function postMessage(channel, message) {
    const transmitterChannel = openTransmitterChannel(channel);
    transmitterChannel.postMessage(message);
}
//# sourceMappingURL=broadcast.js.map