"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const Peer_1 = require("../../../../../api/peer/Peer");
const Semifunctional_1 = require("../../../../../Class/Semifunctional");
const stringify_1 = require("../../../../../spec/stringify");
const EventEmitter_1 = require("../../../../../wrap/EventEmitter");
const MediaStream_1 = require("../../../../../wrap/MediaStream");
const _ids_1 = require("../../../../_ids");
class PeerReceiver extends Semifunctional_1.Semifunctional {
    constructor(system) {
        super({
            fi: ['opt'],
            fo: ['answer'],
            i: ['close', 'offer'],
            o: ['stream', 'emitter'],
        }, {
            input: {},
        }, system, _ids_1.ID_PEER_RECEIVER);
        this._peer = null;
        this._unlisten = undefined;
        this._connected = false;
        this._flag_err_invalid_offer = false;
        this._output_answer = (offer) => __awaiter(this, void 0, void 0, function* () {
            try {
                yield this._peer.acceptOffer(offer);
            }
            catch (err) {
                this._flag_err_invalid_offer = true;
                this.err('invalid offer');
                return;
            }
            const answer = yield this._peer.answer();
            this._output.answer.push(answer);
        });
        this._send_data = (data, callback) => {
            this._send({ type: 'data', data }, callback);
        };
        this._send = (data, callback) => {
            if (this._connected) {
                const message = (0, stringify_1.stringify)(data);
                this._peer.send(message);
                callback();
            }
            else {
                callback(undefined, 'peer not connected');
            }
        };
        this._setup_peer = () => {
            const connect_listener = () => {
                // console.log('Receiver', 'Peer', 'connect')
                this._connected = true;
                const emitter = (0, EventEmitter_1.wrapEventEmitter)(this.__system);
                this._output.emitter.push(emitter);
            };
            const error_listener = (err) => {
                // console.log('Receiver', 'Peer', 'error', err)
                this.err(err.message);
            };
            const close_listener = () => {
                // console.log('Receiver', 'Peer', 'close')
                this._disconnect();
            };
            const message_listener = (message) => {
                // console.log('Receiver', 'Peer', 'message', message)
                if (this._output.emitter.active()) {
                    // @ts-ignore
                    this._output.emitter.peak().emit('message', message);
                }
            };
            const start_listener = (stream) => {
                // console.log('Receiver', 'Peer', 'start', stream)
                const _stream = (0, MediaStream_1.wrapMediaStream)(stream, this.__system);
                this._output.stream.push(_stream);
            };
            const stop_listener = () => {
                // console.log('Receiver', 'Peer', 'stop')
                this._output.stream.pull();
            };
            this._peer.addListener('connect', connect_listener);
            this._peer.addListener('error', error_listener);
            this._peer.addListener('close', close_listener);
            this._peer.addListener('message', message_listener);
            this._peer.addListener('start', start_listener);
            this._peer.addListener('stop', stop_listener);
            return () => {
                this._peer.removeListener('connect', connect_listener);
                this._peer.removeListener('error', error_listener);
                this._peer.removeListener('close', close_listener);
                this._peer.removeListener('message', message_listener);
                this._peer.removeListener('start', start_listener);
                this._peer.removeListener('stop', stop_listener);
            };
        };
        this._disconnect = () => {
            if (this._unlisten) {
                this._unlisten();
                this._unlisten = undefined;
            }
            this._output.emitter.pull();
            this._output.stream.pull();
            if (this._peer) {
                this._peer.close();
                this._peer = null;
            }
            this._connected = false;
            this._done({});
        };
        this.addListener('destroy', () => {
            this._disconnect();
        });
        this.addListener('take_err', () => {
            if (this._flag_err_invalid_offer) {
                this._flag_err_invalid_offer = false;
                this._backward('offer');
            }
            else {
                // TODO
            }
        });
    }
    f({ opt }) {
        return __awaiter(this, void 0, void 0, function* () {
            this._peer = new Peer_1.Peer(this.__system, false, opt);
            this._setup_peer();
            if (this._input.offer.active()) {
                this._output_answer(this._input.offer.peak());
            }
        });
    }
    onDataInputData(name, data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (name === 'close') {
                this._disconnect();
                this._backward('close');
            }
            else if (name === 'offer') {
                if (this._input.opt.active()) {
                    this._output_answer(data);
                }
            }
        });
    }
    onDataInputDrop(name) {
        if (name === 'opt') {
            if (!this._backwarding) {
                this._disconnect();
            }
        }
        else if (name === 'offer') {
            if (this._flag_err_invalid_offer) {
                this._flag_err_invalid_offer = false;
                this.takeErr();
                return;
            }
            this._forward_empty('emitter');
            this._forward_empty('stream');
            this._forward_empty('answer');
        }
    }
    onDataOutputDrop(name) {
        if (name === 'answer') {
            this._input.offer.pull();
        }
    }
}
exports.default = PeerReceiver;
//# sourceMappingURL=index.js.map