var http = require('http');
var ArrayBuffer = require('./typedarrays').ArrayBuffer;
var MemBuffer = require('./MemBuffer').Buffer;

function HttpServerTransport(config) {
    config = config || {};
    this.port = config.port;
    this.pathname = config.pathname;
    this.process = config.process;
    this.webserver = null;
}

HttpServerTransport.prototype.listen = function () {
    var me = this;
    this.webserver = http.createServer(function (req, res) {
        var buffer = new Buffer(0);
        req.on('data', function (chunk) {
            buffer = Buffer.concat([buffer, chunk])
        });
        req.on('end', function () {
            var input = new MemBuffer(new ArrayBuffer(buffer));
            var output = new Transport(res);
            me.process(input, output);
        });
    });
    this.webserver.listen(this.port);
    console.log('thrift http server listening on port: ' + this.port);
};

HttpServerTransport.prototype.close = function () {
    this.webserver.close();
};

function Transport(response) {
    this.response = response;
    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.response.writeHead(200, {
        'Content-Type': 'application/x-thrift'
    });

    this.output.flush();
    this.response.end(this.output.buffer);
    this.clear();
};

exports.ServerTransport = HttpServerTransport;

