var config = require('../config/config');
var md5 = require('./app_md5');
var extend = require('util')._extend;

module.exports = function(req, res, next){
	var params = {},
		keys = [],
		queryString = '',
		sign;
	params = extend(params, req.query);
	params = extend(params, req.body);
	params['app_key'] = config['app_key'];
	if(params['protocol'])
		delete params['protocol'];
	if(params['api_path'])
		delete params['api_path'];

	keys = Object.keys(params);
	keys = keys.sort();

	keys.forEach(function(key){
		if(key !== '' && params[key] !== ''){
			queryString += key + '=' + params[key] + '&';	
		}	
	});

	if(queryString !== ''){
		queryString += config.sign_secret;	
	}
	
	sign = md5(queryString);
	
	if(typeof res.locals === 'undefined' ){
		res.locals = {};	
	}

	res.locals.sign = sign;

	next();
}

