var debug   = require('debug')('rewrite');
var fs      = require('fs');

var DEBUG = process.env.DEBUG && (process.env.DEBUG != "undefined");

function initRules(rules, option) {
    option.forEach(function(rule){
        if (!rule || !rule.from || !rule.to ||
            !(rule.from = rule.from.trim()) ||
            !(rule.to = rule.to.trim())) {
            return false;
        }

        rules.push({from: new RegExp(rule.from), to: rule.to, comment: rule.comment });

        if(DEBUG) debug('register:' + rule.from + ' -> ' + rule.to);

    });
}

/**
 * 返回true表示继续执行，false表示退出后续流程
 */
function pretreat(req, res, next){


    //api请求,走rewriteconfig配置
    if(req.url.indexOf('/api/') == 0){
        return true;
    }

    if(req.url == '/err/404.htm'){
        req.url='/404.html';
        return false;
    }

    //favicon请求
    if(req.url == '/favicon.ico'){
        req.url='/img/favicon.ico';
        return false;
    }

    if(req.url == '/pcauto.jpg'){
        req.url='/img/pcauto.jpg';
        return false;
    }

    //处理空串请求
    if(req.url=='')
        req.url='/';

    // 首页处理
    if(req.url=='/'){
        if(!req.headers || !req.headers.cookie || !req.headers.cookie.match(/regionCity/)){
            req.orginalUrl=req.url;
            req.url='/s/finance/common/location.xsp';
            return false;
        }
        return true;
    }
    
    //非斜杠结尾 或者 非/r1/的url
    if(req.url.match(/jrproxy/)){//处理代理也请求。
        req.url=req.url.replace("jrproxy","x");
        return false;
    }
        
    //非/r1/的url
    if(req.url.match((/\/r\D*\//))){
        return true;
    }

    //如果没有位置信息,或者位置信息里与cookie不一致，走定位模块location.js
    if(!req.url.match((/\/r\d+/)) || relocate(req)){
    // if(!req.url.match((/\/r\d+/))){
        req.orginalUrl=req.url;
        req.url='/s/finance/common/location.xsp';
        return false;
    }

    return true;
};

// url中位置与cookie不一致时，重新定位
function relocate(req){
    var reg = /.*\/r(\d+)\/.*/;
    var ridInUrl = req.url;
    ridInUrl = ridInUrl.replace(reg, "$1");

    //提取cookie中的位置信息  
    reg = /.*regionCity%22%3A(\d+)%2C%22.*/;
    var ridInCookie = req.headers.cookie;
    if(!ridInCookie)
        return true;
    ridInCookie = ridInCookie.replace(reg, "$1");

    if(ridInUrl!=ridInCookie){
        return true;
    }
        
    return false;
}

function handleRewirte(rules, req, res, next){
    if (rules.length) {
            var offset = req.url.toLowerCase().indexOf('?')
            var queryString ='';

            if(offset != -1){
                req.url4rewrite = req.url.substring(0, offset);
                queryString = req.url.substring(offset);
            }else{
                req.url4rewrite = req.url;
            }

            for (var i = 0; i < rules.length; i ++) {
                var rule = rules[i];
                if (rule.from.test(req.url4rewrite)) {
                    req.orginalUrl = req.url;
                    var toUrl = req.url4rewrite.replace(rule.from, rule.to);
                    if (toUrl.indexOf('?') == -1){
                        toUrl = toUrl + queryString;
                    }else{
                        toUrl = toUrl + '&' + queryString.substr(1);
                    }

                    if(toUrl.substr(toUrl.length-1)=="&")toUrl=toUrl.substr(0,toUrl.length-1);
                    req.url = toUrl;
                    if (DEBUG) debug(req.url + ' : ' + rule.from + ' -> ' + toUrl);
                    next();
                    return;
                }
            }
            // WAP页无匹配请求，跳转至404页
           req.url='/404.html';
        }
}

exports = module.exports = function rewriter(option) {
    var rules = [];
    initRules(rules, option);

    //这个函数支持后面加问号
    return function(req, res, next) {
        var go=pretreat(req, res, next);
        if(go){
            handleRewirte(rules, req, res, next);
        }
        next();
    };
};



