"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

const helper_1 = require("./helper");
class PipeTransport {
    constructor(pipeWrite, pipeRead) {
        this._pipeWrite = pipeWrite;
        this._pendingMessage = '';
        this._eventListeners = [
            helper_1.helper.addEventListener(pipeRead, 'data', buffer => this._dispatch(buffer)),
            helper_1.helper.addEventListener(pipeRead, 'close', () => {
                if (this.onclose)
                    this.onclose.call(null);
            }),
            helper_1.helper.addEventListener(pipeRead, 'error', helper_1.debugError),
            helper_1.helper.addEventListener(pipeWrite, 'error', helper_1.debugError),
        ];
        this.onmessage = null;
        this.onclose = null;
    }
    send(message) {
        this._pipeWrite.write(message);
        this._pipeWrite.write('\0');
    }
    _dispatch(buffer) {
        let end = buffer.indexOf('\0');
        if (end === -1) {
            this._pendingMessage += buffer.toString();
            return;
        }
        const message = this._pendingMessage + buffer.toString(undefined, 0, end);
        if (this.onmessage)
            this.onmessage.call(null, message);
        let start = end + 1;
        end = buffer.indexOf('\0', start);
        while (end !== -1) {
            if (this.onmessage)
                this.onmessage.call(null, buffer.toString(undefined, start, end));
            start = end + 1;
            end = buffer.indexOf('\0', start);
        }
        this._pendingMessage = buffer.toString(undefined, start);
    }
    close() {
        this._pipeWrite = null;
        helper_1.helper.removeEventListeners(this._eventListeners);
    }
}
exports.PipeTransport = PipeTransport;
