/**
 *	File: app/helper.js
 *	Author: Gerrit Linnemann
 *	
 *	Swiss-knife.
 */


// load the things we need
var os      = require('os')
,   dns     = require('dns')
,   Log     = require('./logging')
,   Crypto  = require('crypto')
,   interfaceAddresses = require('interface-addresses');


var app = null;
var ConfReader = null;


exports.init = function(express) {
	app = express;
	
	ConfReader = app.get('ConfReader');
	
	return this;
}


exports.timeSince = function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
        return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
}

exports.isJSON = function(toCheck) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

exports.isDefinedAndNotNull = function(toCheck) {
	return (
		typeof toCheck !== 'undefined' &&
		toCheck != null
	);
}

exports.cnt = function(db) {
	var cnt = 0;

	if(db.constructor === Array) {	// do it the array-way
		cnt = db.length;
		
	} else {	// oh boy, no array ...
		var cnt_ = 0;
		for (var key_ in db) { cnt_++; }
		cnt = cnt_;		
	}
	
	return cnt;
}

exports.each = function(db, callback) {
	if(db.constructor === Array) {	// do it the array-way
		for(i=0; i < db.length; i++) {
			var entry = db[i];
			var isLast = ((i+1) == db.length);
			
			callback(entry, isLast);
		}
		
	} else {	// oh boy, no array ...
		var cnt_ = 0;
		for (var key_ in db) { cnt_++; }
		
		var cnt = 0;
		for (var key in db) {
			cnt++;
			var entry = db[key];
			
			callback(entry, (cnt_==cnt));
		}
		
	}
}

exports.checkValueEquality = function(foo, bar) {
	return doValueEqualityCheck(foo, bar);
}

exports.simpleHash = function(foo) {
  var hash = Crypto.createHash('md5').update(foo).digest('hex');
  return hash;
}

/* private */
function doValueEqualityCheck(foo, bar) {
	var key;
	for(key in foo) {
		Log.debug( "Compare \"" + foo[key] + "\" with \"" + bar[key] + "\" for key \"" + key + "\"" );
		
		if(typeof foo[key] === 'object' && typeof bar[key] === 'object') {
			var isEquals = doValueEqualityCheck(foo, bar);
			
			if(!isEquals) {
				return false;
			}
		} else {
			if(foo[key].localeCompare(bar[key]) != 0) {
				return false;
			}
		}
	}
	
	return true;
}