var net = require('net');
var MemBuffer = require('./MemBuffer');
var AsyncMemBuffer = require('./AsyncMemBuffer');

function NamedPipeServerTransport(config) {
    config = config || {};
    this.pipename = config.pipename;
    this.process = config.process;
    this.server = null;
}

NamedPipeServerTransport.prototype.listen = function () {
    var me = this;

    this.server = net.createServer(function (socket) {
        var input = new AsyncMemBuffer();
        var firstByteReceived = false;

        socket.on('readable', function () {
            var chunk;
            var output;
            while (null != (chunk = socket.read())) {
                input.write(chunk);
                input.flush();

                if (chunk && chunk.length > 0 && !firstByteReceived) {
                    firstByteReceived = true;
                    input.on('readMessageEnd', function () {
                        input.clear();
                        firstByteReceived = false;
                    });
                    output = new Transport(socket);
                    me.process(input, output);
                }
            }
        });
		socket.on('error', function (err) {
			console.log('socket error: ' + err);
		});
    });
	
	this.server.on('error', function (err) {
		console.log('Server network error: ' + err);
	});

    this.server.listen(this.pipename);
};

NamedPipeServerTransport.prototype.close = function () {
    this.server.close();
};

function Transport(socket) {
    this.socket = socket;
    this.output = new MemBuffer();
}

Transport.prototype.write = function (bytes) {
    this.output.write(bytes);
};

Transport.prototype.clear = function (bytes) {
    this.output.clear();
};

Transport.prototype.flush = function () {
    this.output.flush();
	//this.socket.write(this.output.buffer);
    this.socket.end(this.output.buffer);
    this.clear();
};

module.exports = NamedPipeServerTransport;

