"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataChannel = void 0;
const ref_napi_1 = __importDefault(require("ref-napi"));
const events_1 = require("./events");
const Handler_DataChannelOnData_1 = require("./events/Handler_DataChannelOnData");
const impls_1 = require("./events/impls");
const native_1 = require("./native");
/**
 * A data channel from our device to another Peer on the Rainway Network.
 */
class DataChannel extends events_1.EventEmitter {
    /** @internal */
    constructor(peer, mode, id) {
        super();
        this.peer = peer;
        this.mode = mode;
        this.id = id;
        this._onData = new Handler_DataChannelOnData_1.Handler_DataChannelOnData((ev) => {
            const data = ev.data.buffer.slice(0, Number(ev.len).valueOf());
            const message = new Uint8Array(data);
            this.emit("message", new impls_1.MessageEvent(message));
        });
        (0, native_1.invokeOrError)("rainway_peer_connection_set_data_channel_data_handler", () => native_1.native.rainway_peer_connection_set_data_channel_data_handler(this.peer.connection.id.toString(), this.peer.id.toString(), this.id, this._onData.handler));
    }
    /**
     * Sends a binary message via this data channel.
     * If a string is given, it will be utf-8 encoded before transmission.
     * @param data - data to transmit
     */
    send(data) {
        let buffer;
        if (typeof data === "string") {
            buffer = new TextEncoder().encode(data);
        }
        else {
            buffer = data;
        }
        // TODO(bengreenier): test test
        const msg = Buffer.from(buffer);
        msg.type = ref_napi_1.default.types.uint8;
        (0, native_1.invokeOrError)("rainway_peer_connection_data_channel_send", () => native_1.native.rainway_peer_connection_data_channel_send(this.peer.connection.id.toString(), this.peer.id.toString(), this.id, msg, buffer.length));
    }
}
exports.DataChannel = DataChannel;
//# sourceMappingURL=data-channel.js.map