let cryptoApi = {},
	crypto = require('crypto'),
	semusiConfig = require('./../config');

(function (cryptoApi) {
	
	let password = semusiConfig.cryptoPassword;
	let salt = semusiConfig.cryptoSalt;

	let shaHash2 = crypto.createHash(semusiConfig.shaV2Hash);
	shaHash2.update(salt);
	let hash = shaHash2.digest();	
	let key = crypto.pbkdf2Sync(password, hash, 1000, 32,semusiConfig.shaV2Hash);	
	let iv = new Buffer(16);
	iv.fill(0);	
	let algorithm = 'aes-256-cbc';

	cryptoApi.encryptV2 = function(res,text){
		try{
			let cipher = crypto.createCipheriv(algorithm, key, iv);
			let crypted = cipher.update(text,'utf8','base64');
			crypted += cipher.final('base64');
			return crypted;		
		}
		catch(e){
			return '';
		}
	  
	}

	cryptoApi.decryptV2 = function(res,text){
		try{
		  	let decipher = crypto.createDecipheriv(algorithm, key, iv);
		  	let dec = decipher.update(text,'base64','utf8');
		  	dec += decipher.final('utf8');
		  	return dec;
		}
		catch(e){
			returnMessageV2(res,"Error while decrypting request");
			return false;
		}
	}

	cryptoApi.encryptV1 = function(res,text) {
		try{
			let key = semusiConfig.cryptoKey;
			let iv = semusiConfig.cryptoIV;
	        let cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
	        let crypted = cipher.update(text, 'utf8', 'base64');
	        
	        crypted += cipher.final('base64');
	        return crypted;	
		}
		catch(e){
			return '';
		}
	}

	cryptoApi.decryptV1 = function(res,cipher) {
		try{
			let key = semusiConfig.cryptoKey;
			let iv = semusiConfig.cryptoIV;
	        let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
	        decipher.setAutoPadding(false);
	        let decrypted = decipher.update(cipher, 'base64', 'utf8');
	        decrypted += decipher.final('utf8');

	        return decrypted;
    	}
    	catch(e){
			returnMessageV1(res,"Error while decrypting request");
			return false;
		}
	}

	function returnMessageV1(res,msg){
		res.writeHead(500, {'Content-Type': 'application/json; charset=utf-8'});
		res.write(cryptoApi.encryptV1(res,JSON.stringify({result: msg})));
		res.end();
	}
	function returnMessageV2(res,msg){
		res.writeHead(500, {'Content-Type': 'application/json; charset=utf-8'});
		res.write(cryptoApi.encryptV2(res,JSON.stringify({result: msg})));
		res.end();
	}

}(cryptoApi));

module.exports = cryptoApi;		