/**
 * @fileOverview [Node.js zlib module](http://nodejs.org/docs/v0.8.22/api/zlib.html) tests
 * with `'accept-encoding': 'gzip'` http request
 */

var http = require('http'),
    zlib = require('zlib'),

    rqopts = {
        host : 'api.twitter.com',
        path : '/1/trends/1.json',
        headers: { 'accept-encoding': 'gzip,*' }
    };

function onResStream(res) {
    console.log('\nUsing streams');
    res
        .pipe(zlib.createGunzip())
        .pipe(process.stdout);
}

function onResBuffer(res) {
    var buf = [];
    res
        .on('data', function(chunk) {
            buf.push(chunk);
        })
        .on('end', function() {
            zlib.gunzip(Buffer.concat(buf), function(err, data) {
                console.log('\nUsing buffer');

                if(err) {
                    console.log(err.message);
                    return;
                }

                console.log(data.toString());
            });
        });
}

function onResStrings(res) {
    var buf = '';
    res
        .on('data', function(chunk) {
            buf += chunk;
        })
        .on('end', function() {
            zlib.gunzip(buf, function(err, data) {
                console.log('\nUsing strings');

                if(err) {
                    console.log(err.message);
                    return;
                }

                console.log(data.toString());
            });
        });
}

function onResPiped(res) {
    var gzip = zlib.createGunzip();
    res.pipe(gzip);

    var buf = '';
    gzip
        .on('data', function(chunk) {
            buf += chunk;
        })
        .on('end', function() {
            console.log('\nUsing streams with pipe');
            console.log(buf + '');
        });
}


http.get(rqopts, onResStream);
http.get(rqopts, onResBuffer);
http.get(rqopts, onResStrings);
http.get(rqopts, onResPiped);