var fs = require('fs');

var Q = require('q');


var counter = 0;

var speed = 0;


// constructor

function bbbPWM(pwmPath, period) {

   this.period = period;

   this.runPath = pwmPath + 'run';

   this.dutyPath = pwmPath + 'duty';

   this.periodPath = pwmPath + 'period';

   this.polarityPath = pwmPath + 'polarity';

   this.go = go;

   this.incSpeed = incSpeed;

   this.decSpeed = decSpeed;

   this.turnOn = turnOn;

   this.turnOff = turnOff;

   this.setSpeed = setSpeed;

   this.getSpeed = getSpeed;

   this.configureDevice();

   counter++;

}


bbbPWM.prototype.writeFile = function(file, content) {

   try {

       fs.writeFile(file, content);

   } catch (e) {

       console.log('writeFile error: ' + e);

   }

};


bbbPWM.prototype.setDuty = function(duty) {

   var deferred = Q.defer();

   var duty;

   duty = Number(duty);

   try {

       fs.writeFile(DUTY_PATH, Math.floor(Number(duty) * 1000));

   } catch (e) {

       console.log('setDuty error: ' + e);

   }

   return deferred.promise;

};


function getSpeed( ) {

   return this.speed;

}


function setSpeed(mySpeed) {

   this.speed = mySpeed;

}


function incSpeed( ) {

   if (this.speed < 45) {

       this.speed = this.speed + 2;

   }

}


function decSpeed( ) {

   if (this.speed > 6) {

       this.speed = this.speed - 2;

   }

}


function go( ) {

   duty = Math.floor(this.speed * 500 * 1000);

   try {

       fs.writeFile(this.dutyPath, duty);

   } catch (e) {

       console.log('bbbPWM.go() error: ' + e);

   }

};


function turnOn( ) {

   this.writeFile(this.runPath, '1');

};


function turnOff( ) {

   speed = 0;

   this.writeFile(this.runPath, '0');

};


bbbPWM.prototype.configureDevice = function( ) {

   myCounter = Number(counter);

   try {

       fs.writeFile(this.runPath, '0'); // stop on init

       fs.writeFile(this.periodPath, this.period);

       fs.writeFile(this.polarityPath, '0');

       fs.writeFile(this.dutyPath, 0 * 500 * 1000); // duty start value


       var content;

       // First I want to read the file

       fs.readFile(this.runPath, function read(err, data) {

           if (err) {

               throw err;

           }

           content = data;

           processFile(); // put the next step in a function and invoke it

       });


       function processFile( ) {

           console.log(content);

       }


       fs.readFile(this.runPath, data);

       content = data;

       console.log(data);


   } catch (e) {

       console.log('configureDevice error: ' + e);

   }

};


bbbPWM.errorHandler = function(error) {

   console.log('kucha.');

   console.log('Error: ' + error.message);

};


module.exports = bbbPWM;