// Dependencies
var fs = require('fs'),
	url = require('url'),
	http = require('http'),
	exec = require('child_process').exec,
	spawn = require('child_process').spawn,
    wrench = require('wrench');

console.log('>> Fetching PhantomJS');

// App variables
var file_url = null,
    DOWNLOAD_DIR = 'phantom/';

// check th os
switch (process.platform) {
    case 'linux':
    case 'linux2':
        file_url = 'http://phantomjs.googlecode.com/files/phantomjs-1.5.0-linux-x86-dynamic.tar.gz';
        break;
    case 'darwin':
        file_url = 'http://phantomjs.googlecode.com/files/phantomjs-1.5.0-macosx-static.zip';
        break;
    default:
        file_url = 'http://phantomjs.googlecode.com/files/phantomjs-1.5.0-win32-static.zip';
        break;         
}

fs.mkdir(DOWNLOAD_DIR, function () {
	download_file_httpget(file_url);
});

// Function to download file using HTTP.get
var download_file_httpget = function(file_url) {
    var options = {
        host: url.parse(file_url).host,
        port: 80,
        path: url.parse(file_url).pathname
    };

    var file_name = url.parse(file_url).pathname.split('/').pop();
    var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);

    http.get(options, function(res) {
        res.on('data', function(data) {
                file.write(data);
            }).on('end', function() {
                file.end();
                console.log('>> Deflating PhantomJS');
                exec('unzip ' + DOWNLOAD_DIR + file_name, function () {
                	console.log(DOWNLOAD_DIR + file_name);
                    //fs.renameSync('./phantomjs-1.5.0/bin/phantomjs', DOWNLOAD_DIR + '/phantomjs');
                });
            });
    });
};