"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var xhr_1 = require("@dojo/core/request/providers/xhr");
var Task_1 = require("@dojo/core/async/Task");
var Channel = (function () {
    function Channel(options) {
        this.sessionId = options.sessionId;
        this.url = options.url;
        this._sequence = 1;
        this._messageBuffer = [];
    }
    Channel.prototype.sendMessage = function (name, data) {
        if (data instanceof Error) {
            data = { name: data.name, message: data.message, stack: data.stack };
        }
        return this._sendData(name, data);
    };
    Channel.prototype._sendData = function (name, data) {
        var _this = this;
        var id = String(this._sequence++);
        var sessionId = this.sessionId;
        var message = { id: id, sessionId: sessionId, name: name, data: data };
        this._messageBuffer.push(JSON.stringify(message));
        if (this._activeRequest || this._pendingRequest) {
            if (!this._pendingRequest) {
                this._pendingRequest = this._activeRequest.then(function () {
                    _this._pendingRequest = null;
                    return _this._send();
                });
            }
            return this._pendingRequest;
        }
        return this._send();
    };
    Channel.prototype._send = function () {
        var _this = this;
        var sendNextBlock = function () {
            var block = [messages.shift()];
            var size = block[0].length;
            while (messages.length > 0 && size + messages[0].length < exports.maxPostSize) {
                size += messages[0].length;
                block.push(messages.shift());
            }
            return xhr_1.default(_this.url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(block)
            }).then(function () {
                if (messages.length > 0) {
                    return sendNextBlock();
                }
            });
        };
        var messages = this._messageBuffer;
        this._messageBuffer = [];
        this._activeRequest = new Task_1.default(function (resolve, reject) {
            return sendNextBlock().then(function () {
                _this._activeRequest = null;
                resolve();
            }, function (error) {
                _this._activeRequest = null;
                reject(error);
            });
        });
        return this._activeRequest;
    };
    return Channel;
}());
exports.default = Channel;
function isChannel(value) {
    return value && typeof value === 'object' && typeof value.sendMessage === 'function';
}
exports.isChannel = isChannel;
//# sourceMappingURL=Channel.js.map