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

function BinaryHttpTransport (serviceUrl) {
    var parsedUrl = url.parse(serviceUrl);
    this.hostname = parsedUrl.hostname;
    this.port = parsedUrl.port;
    this.path = parsedUrl.path;
    this.url = parsedUrl.href;

    this.input = new MemBuffer();
};

BinaryHttpTransport.prototype.open = function () {
};

BinaryHttpTransport.prototype.close = function () {
};

BinaryHttpTransport.prototype.read = function (len) {
    throw Error('BinaryHttpTransport object does not support reads');
};

BinaryHttpTransport.prototype.write = function (bytes) {
    this.input.write(bytes);
};

BinaryHttpTransport.prototype.clear = function () {
    this.input.clear();
};

BinaryHttpTransport.prototype.flush = function (onsuccess, onerror) {
    var me = this;
    var options = {
        hostname: this.hostname,
        port: this.port,
        path: this.path,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-thrift',
            'Accept': 'application/x-thrift'
        }
    };
    var req;
    onerror = onerror || onsuccess;

    req = http.request(options, function (res) {
        var chunkCount = 0;
        if (res.statusCode != 200) {
            console.log('Error in Thrift HTTP response: ' + err.statusCode);
            if (onerror) onerror(res);
        }
        res.on('data', function (chunk) {
            if (++chunkCount > 1) throw Error('Multiple chunks not supported in BinaryHttpTransport');
            if (onsuccess) {
                onsuccess(new MemBuffer(new ArrayBuffer(chunk)));
            }
        });
    });

    req.on('error', function (err) {
        console.log('Error making Thrift HTTP request: ' + err);
        if (onerror) onerror(err);
    });

    this.input.flush();
    req.write(this.input.buffer);
    req.end();
    this.clear();
};

exports.Transport = BinaryHttpTransport;

