import { __awaiter } from "tslib";
import { RTC } from './rtc';
export class Session {
    constructor(cli, rpc) {
        this.cli = cli;
        this.rtc = new RTC();
        this.id = '';
        this.answered = false;
        this.incoming = false;
        this.rpc = rpc;
    }
    call(destination = '') {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.rtc.initLocalMediaStream();
            yield this.rtc.createOffer();
            const result = yield this.rpc.request(`call_sdp`, {
                destination,
                sdp: this.rtc.localSdp,
            });
            this.id = result.sip_id;
        });
    }
    answer(s) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise(() => __awaiter(this, void 0, void 0, function* () {
                const { callId } = s;
                if (!this.callId) {
                    this.callId = callId;
                }
                const result = yield this.rpc.request(`call_sdp_remote`, {
                    id: this.callId,
                });
                yield this.rtc.initLocalMediaStream();
                yield this.rtc.createAnswer(result.sdp);
                yield this.rpc.request(`call_sdp_answer`, {
                    id: this.callId,
                    sdp: this.rtc.localSdp,
                });
                this.cli.emitSessionMedia(this);
            }));
        });
    }
    recovery(callId) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.rtc.initLocalMediaStream();
            yield this.rtc.createOffer();
            const result = yield this.rpc.request(`call_sdp_recovery`, {
                id: callId,
                sdp: this.rtc.localSdp,
            });
            this.id = result.sip_id;
            return this.id;
        });
    }
    get localStream() {
        return this.rtc.localStream;
    }
    get peerStream() {
        return this.rtc.peerStream;
    }
    getLocalMedia() {
        if (this.localStream) {
            return [this.localStream];
        }
        return [];
    }
    getPeerMedia() {
        if (this.peerStream) {
            return [this.peerStream];
        }
        return [];
    }
    destroy() {
        return __awaiter(this, void 0, void 0, function* () {
            this.rtc.clean();
        });
    }
    handleAnswerFromOffer(answer) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.answered) {
                throw new Error('Answered');
            }
            this.answered = true;
            yield this.rtc.handleAnswerFromOffer(answer);
        });
    }
}
//# sourceMappingURL=session.js.map