#! /usr/bin/env node

/*
 * speedtest
 * https://github.com/craigwermert/speedtest
 *
 * Copyright (c) 2014 Craig Wermert
 * Licensed under the MIT license.
 */
 var fs = require('fs');
 var request = require('request');
 var progress = require('request-progress');
 var moment = require('moment');
 var path = require('path');
 require('shelljs/global');

 var end;
 var received = [];
 var total;
 // Note that the options argument is optional
 var start = Date.now();
 console.log("START: " + Date.now())
 progress(request('http://speedtest.wdc01.softlayer.com/downloads/test10.zip'),{
  progress: 2000
 })
 .on('progress', function (state) {
    total = state.total;
     console.log('received ', (state.received/1024000).toFixed(2) + 'Mb ' + state.percent + '%');
 })
 .pipe(fs.createWriteStream('test.zip'))

 .on('close', function (err) {

     end = Date.now();
     function showResults() {
         var duration = Math.round((end - start) / 1000);
         var bitsLoaded = total * 8;
         var speedBps = Math.round(total / duration);
         var speedKbps = (speedBps / 1024).toFixed(2);
         var speedMbps = (speedKbps / 1024).toFixed(2);
         return moment().format() + "," + speedKbps + "," + speedMbps + "\n";
     }
     var logfile = path.join(__dirname, '..', 'log.csv');
     fs.exists(logfile, function (exists) {
       if(exists === true){
        fs.appendFile(logfile, showResults(), function (err) {});
      } else {
        fs.writeFile(logfile, 'date,kbps,mbps\n', function (err) {
          if (err) throw err;
          fs.appendFile(logfile, showResults(), function (err) {});
        });
      }
     });
     
     exec('rm test.zip');
 });