var urlencode = require('urlencode');
exports=module.exports=function(logger,rest,settings){   
	function encodeUrl(url){
		return urlencode(url);
	}

	function encodePamars(params){
		var temp=[];
		for(var i=0;i<params.length;i++){
			var param=params[i];
			var tempParam=param.split("=")
			tempParam[1]=urlencode.decode(tempParam[1], 'utf8');
			tempParam[1]=tempParam[1].replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
			console.log(tempParam[1]);
			if(i<(params.length-1)){
				if(/[:&+/?%#=]/g.test(tempParam[1])){
					temp.push(tempParam[0]+"="+encodeUrl(tempParam[1])+"&");
				}else{
					temp.push(tempParam[0]+"="+tempParam[1]+"&");
				} 
			}else{
				if(/[:&+/?%#=]/g.test(tempParam[1])){
					temp.push(tempParam[0]+"="+encodeUrl(tempParam[1]));
				}else{
					temp.push(tempParam[0]+"="+tempParam[1]);
				}  
			}
		} 
		return temp.join("");
	}

	function handlePamars(url){
		var tempUrl=url;
		// if(url.indexOf("?")!=-1){
		// 	var temp=url.split("?");
		// 	var params=""; 
		// 	if(temp[1]&&temp[1].indexOf("&")!=-1){
		// 		params=encodePamars(temp[1].split("&"));
		// 	}else{
		// 		params=encodePamars([temp[1]]);
		// 	}
		// 	return temp[0]+"?"+params;
		// }else {
		// 	return tempUrl;
		// } 
		return tempUrl;
	}

	function splitServiceFromUrl(url){
		var catalog=url.substring(1,url.indexOf('/',1));
		var pathUrl=url.substring(url.indexOf('/',1));
		var fullPath=settings.restful.url+catalog+settings.restful.version+pathUrl; 
		if(pathUrl&&pathUrl.indexOf('inits')!=-1){
			fullPath=settings.restful.url+catalog+'/v2'+pathUrl; 
		}
		return fullPath
	}

	function splitUrl(fullUrl){
		if(settings.prefix&&settings.prefix.length>1){
			fullUrl=fullUrl.substring(settings.prefix.length-1);
		}
		var url=fullUrl.substring(9);
		return url;
	}

	function searchService(services,name){
		if(services[name]){
			console.log(services[name]);
			return false;
		}else{
			return true;
		}
	}

	function checkReq(req,res){
		var flag=true;
		// if(flag&&req.headers&&!req.headers['service-catalog']){
		// 	res.status(400);
		// 	res.send({"errors":{},"message":"缺少必要请求参数,服务目录名称是必填项"}); 
		// 	flag=false;
		// }
		// if(flag&&req.session.passport&&req.session.passport.user&&!req.session.passport.user.service_catalog){
		// 	res.status(404);
		// 	res.send({"errors":{},"message":"服务目录未加载,请重新登录"}); 
		// 	flag=false;
		// }
		// if(flag&&searchService(req.session.passport.user.service_catalog,req.headers['service-catalog'])){
		// 	res.status(404);
		// 	res.send({"errors":{},"message":"服务目录未查询到请求服务,请确认参数正确"}); 
		// 	flag=false; 
		// }
		return flag;
	}

	function checkJson(req){ 
		if(req.headers&&req.headers['content-type']=='application/json'){
			return true;
		}else{
			return false;
		}
	}

	function get(req,res,next){ 
		var url=splitUrl(req.originalUrl);
		url=handlePamars(url);
		url=splitServiceFromUrl(url);
		if(checkReq(req,res)){ 
			var options={ 
				'service_catalog':'',
				'url':url,
				'useUrl':true,
				'params':req.body,
				'callback':_cb,
				'req':req,
				'res':res,
				'options':{}
			};  
			rest.get(options);
		}   
		function _cb(data,response){ 
			logger.info('back data:',data); 
			if(response.statusCode<300&&!data){ 
				res.send({
					code:200,
					message:'操作成功!'
				});
			}else {
				res.send(data);
			} 
		} 	 
	}

	function post(req,res,next){
		var url=splitUrl(req.originalUrl); 
		url=splitServiceFromUrl(url);
		if(checkReq(req,res)){ 
			var options={ 
				'service_catalog':'services[catalog].public_endpoint',
				'url':url,
				'useUrl':true,
				'params':req.body,
				'callback':_cb,
				'req':req,
				'res':res,
				'options':{} 
			};
			if(checkJson(req)){
				rest.postJson(options);
			}else{
				rest.post(options);
			} 
		}   
		function _cb(data,response){ 
			logger.info('back data:',data);  
			if(response.statusCode<300&&!data){ 
				res.send({
					code:200,
					message:'操作成功!'
				});
			}else{
				res.send(data);
			} 
		}
	}

	function put(req,res,next){
		var url=splitUrl(req.originalUrl);
		url=splitServiceFromUrl(url);
		if(checkReq(req,res)){ 
			var options={ 
				'service_catalog':'services[catalog].public_endpoint',
				'url': url,
				'useUrl':true,
				'params':req.body,
				'callback':_cb,
				'req':req,
				'res':res,
				'options':{} 
			};
			if(checkJson(req)){
				rest.putJson(options);
			}else{
				rest.put(options);
			}
		}   
		function _cb(data,response){ 
			logger.info('back data:',data); 
			if(response.statusCode<300&&!data){ 
				res.send({
					code:200,
					message:'操作成功!'
				});
			}else{
				res.send(data);
			} 
		}
	}

	function patch(req,res,next){
		var url=splitUrl(req.originalUrl);
		url=splitServiceFromUrl(url);
		if(checkReq(req,res)){ 
			var options={ 
				'service_catalog':'services[catalog].public_endpoint',
				'url': url,
				'useUrl':true,
				'params':req.body,
				'callback':_cb,
				'req':req,
				'res':res,
				'options':{} 
			};
			if(checkJson(req)){
				rest.patchJson(options);
			}else{
				rest.patch(options);
			}
		}   
		function _cb(data,response){ 
			logger.info('back data:',data); 
			res.send(data);
		}
	}

	function head(req,res,next){
		var url=splitUrl(req.originalUrl);
		url=splitServiceFromUrl(url);
		if(checkReq(req,res)){ 
			var options={ 
				'service_catalog':'services[catalog].public_endpoint',
				'url': url,
				'useUrl':true,
				'params':req.body,
				'callback':_cb,
				'req':req,
				'res':res,
				'options':{} 
			};
			rest.get(options);
		}   
		function _cb(data,response){ 
			logger.info('back data:',data); 
			res.send(data);
		}
	}

	function del(req,res,next){ 
		var url=splitUrl(req.originalUrl);
		url=splitServiceFromUrl(url);
		if(checkReq(req,res)){ 
			var options={ 
				'service_catalog':'services[catalog].public_endpoint',
				'url': url,
				'useUrl':true,
				'params':req.body,
				'callback':_cb,
				'req':req,
				'res':res,
				'options':{} 
			};
			rest.del(options);
		}   
		function _cb(data,response){ 
			logger.info('back data:',data); 
			if(response.statusCode<300){
		   		res.send({'action':'delete',"message":"删除成功"});
		   	}else{
				res.send(data);
			}  
		}
	}

	return { 
		'get':get,
		'post':post,
		'put':put,
		'patch':patch,
		'head':head,
		'delete':del
	};
};

exports['@singleton']=true;
exports['@require']=['igloo/logger','utils/rest','igloo/settings'];