var co = require('co');
var fs = require('fs');
var hbs = require('handlebars');
var iconv = require('iconv-lite');
var qS = require('querystring');
var r = require('../../../lib/r.js');
var path  = require('../../../conf/config.js').config().path;

var template = hbs.compile(fs.readFileSync('./scripts/finance/common/location.html').toString());

exports.handle = function(req,rh,maxAge,transEnc,queryString,callback) {
	co(function *() {
	try{
            var param = qS.parse(queryString);
            var data = {};

            var ridInUrl;
            if(req.orginalUrl.match((/\/r\d+/))){
                  var reg = /.*\/r(\d+)\/.*/;
                  ridInUrl = req.orginalUrl;
                  ridInUrl = ridInUrl.replace(reg, "$1");
            }

            data.ridInUrl=ridInUrl;
            data.originalUrl=req.orginalUrl;
            data.host=req.headers.host+path;

            if(param.fmt === 'json') {
                  rh.setHeader('Content-Type','application/json;charset=UTF-8');
                  rh.setBody(data);
            }else {
                  rh.setHeader('Content-Type','text/html;charset=UTF-8');
                  var html = template(data);
                  rh.setHeader('Cache-Control','max-age='+(maxAge));
                  rh.setBody(html);
            }
            callback(null, rh);

	}catch(e) {
		console.error(e);
		callback(e);
	}
	})();
}