"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const base64 = __importStar(require("base64-js"));
const event_target_shim_1 = require("event-target-shim");
const react_native_1 = require("react-native");
const EventEmitter_1 = require("./EventEmitter");
const MessageEvent_1 = __importDefault(require("./MessageEvent"));
const RTCDataChannelEvent_1 = __importDefault(require("./RTCDataChannelEvent"));
const { WebRTCModule } = react_native_1.NativeModules;
const DATA_CHANNEL_EVENTS = ['open', 'message', 'bufferedamountlow', 'closing', 'close', 'error'];
class RTCDataChannel extends event_target_shim_1.defineCustomEventTarget(...DATA_CHANNEL_EVENTS) {
    constructor(info) {
        super();
        this.binaryType = 'arraybuffer'; // we only support 'arraybuffer'
        this.bufferedAmountLowThreshold = 0;
        this._peerConnectionId = info.peerConnectionId;
        this._reactTag = info.reactTag;
        this._bufferedAmount = 0;
        this._label = info.label;
        this._id = info.id === -1 ? null : info.id; // null until negotiated.
        this._ordered = Boolean(info.ordered);
        this._maxPacketLifeTime = info.maxPacketLifeTime;
        this._maxRetransmits = info.maxRetransmits;
        this._protocol = info.protocol || '';
        this._negotiated = Boolean(info.negotiated);
        this._readyState = info.readyState;
        this._registerEvents();
    }
    get bufferedAmount() {
        return this._bufferedAmount;
    }
    get label() {
        return this._label;
    }
    get id() {
        return this._id;
    }
    get ordered() {
        return this._ordered;
    }
    get maxPacketLifeTime() {
        return this._maxPacketLifeTime;
    }
    get maxRetransmits() {
        return this._maxRetransmits;
    }
    get protocol() {
        return this._protocol;
    }
    get negotiated() {
        return this._negotiated;
    }
    get readyState() {
        return this._readyState;
    }
    send(data) {
        if (typeof data === 'string') {
            WebRTCModule.dataChannelSend(this._peerConnectionId, this._reactTag, data, 'text');
            return;
        }
        // Safely convert the buffer object to an Uint8Array for base64-encoding
        if (ArrayBuffer.isView(data)) {
            data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
        }
        else if (data instanceof ArrayBuffer) {
            data = new Uint8Array(data);
        }
        else {
            throw new TypeError('Data must be either string, ArrayBuffer, or ArrayBufferView');
        }
        const base64data = base64.fromByteArray(data);
        WebRTCModule.dataChannelSend(this._peerConnectionId, this._reactTag, base64data, 'binary');
    }
    close() {
        if (this._readyState === 'closing' || this._readyState === 'closed') {
            return;
        }
        WebRTCModule.dataChannelClose(this._peerConnectionId, this._reactTag);
    }
    _registerEvents() {
        EventEmitter_1.addListener(this, 'dataChannelStateChanged', (ev) => {
            if (ev.reactTag !== this._reactTag) {
                return;
            }
            this._readyState = ev.state;
            if (this._id === null && ev.id !== -1) {
                this._id = ev.id;
            }
            if (this._readyState === 'open') {
                // @ts-ignore
                this.dispatchEvent(new RTCDataChannelEvent_1.default('open', { channel: this }));
            }
            else if (this._readyState === 'closing') {
                // @ts-ignore
                this.dispatchEvent(new RTCDataChannelEvent_1.default('closing', { channel: this }));
            }
            else if (this._readyState === 'closed') {
                // @ts-ignore
                this.dispatchEvent(new RTCDataChannelEvent_1.default('close', { channel: this }));
                // This DataChannel is done, clean up event handlers.
                EventEmitter_1.removeListener(this);
                WebRTCModule.dataChannelDispose(this._peerConnectionId, this._reactTag);
            }
        });
        EventEmitter_1.addListener(this, 'dataChannelReceiveMessage', (ev) => {
            if (ev.reactTag !== this._reactTag) {
                return;
            }
            let data = ev.data;
            if (ev.type === 'binary') {
                data = base64.toByteArray(ev.data).buffer;
            }
            // @ts-ignore
            this.dispatchEvent(new MessageEvent_1.default('message', { data }));
        });
        EventEmitter_1.addListener(this, 'dataChannelDidChangeBufferedAmount', (ev) => {
            if (ev.reactTag !== this._reactTag) {
                return;
            }
            this._bufferedAmount = ev.bufferedAmount;
            if (this._bufferedAmount < this.bufferedAmountLowThreshold) {
                // @ts-ignore
                this.dispatchEvent(new RTCDataChannelEvent_1.default('bufferedamountlow', { channel: this }));
            }
        });
    }
}
exports.default = RTCDataChannel;
//# sourceMappingURL=RTCDataChannel.js.map