var os = require('os');
var url = require('url');
var http = require('http');
var attempt = require('attempt');
var log4js = require('log4js');
var logger = log4js.getLogger();
var healthcheck = require('serverdzen-module');

var config = require('config');
var argv = process.argv.slice(2);
if (!argv || argv.length == 0) {
    throw "Error: please, provide your userkey as first parameter!";
}
var userKey = argv[0];

function registerMachine(callback) {
    var data = {
        'UserKey': userKey,
        'ComputerName': os.hostname(),
        'OS': os.type() + ' ' + os.release()
    };
    sendPOST(data, '/machine', callback);
}

function sendHealthcheck(hc, callback) {
    sendPOST(hc, '/', callback);
}

function sendPOST(postData, path, callback) {
    var data = JSON.stringify(postData);
    var options = getOpts(config.get('api.url'), 'POST', path, data);
    var req = http.request(options, function (res) {
        var resData = '';
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            resData += chunk;
        });
        res.on('end', function () {
            callback(res.statusCode != 200 ? res.statusCode : null, resData);
        });
    });
    req.on('error', function (err) {
        callback(err);
    });
    req.write(data);
    req.end();
}

function getOpts(apiUrl, method, path, data) {
    var options = url.parse(apiUrl + '/v'+config.get('api.v')+path);
    options.method = method;
    options.headers = {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(data)
    }
    return options;
}

attempt(
    {
        retries: 5,
        interval: 3000
    }, 
    function() {
        registerMachine(this);
    }, 
    function(err, res) {
        if (err) { 
            logger.error(err);
            throw err;
        }
        logger.debug(res);

            healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) {
                if (err) throw err;
                logger.debug('Healthcheck: ' + JSON.stringify(res));
                logger.debug('Sending data to API...');
                sendHealthcheck(res, function (err, data) {
                    if (err) {
                        logger.error(err);
                    }
                    else {
                        var json = JSON.parse(data);
                        logger.debug('Got response: ' + data);
                        var newInterval = json.Interval * 1000;
                        if (newInterval != timeout) {
                            logger.debug('Changing data collection interval: ');
                            timeout = newInterval;
                        }
                    }
                });
            });
            
            setTimeout(function () {
                gatherHealthCheck(timeout);
            }, timeout);
        })(machineContainer.Settings.Interval * 1000);
    });
        var machineContainer = JSON.parse(res);
        (function gatherHealthCheck(timeout) {
            logger.debug('Getting healthcheck...')
