var debug = require('debug')('@gopalroy/test-drive');

module.exports = {
    // 把由'/'引用起来的字符串转换为RegExp,其它返回原始字符串
    parseRegExp: function(strBuffer){
        if(strBuffer && strBuffer.length > 2
            && strBuffer[0] === '/'
            && strBuffer[strBuffer.length-1] === '/')
        {
            // 是正则表达式
            return new RegExp(strBuffer.substr(1, strBuffer.length-2));
        }
        else // 不是正则表达式
            return strBuffer;
    },
    // 把HTTP请求中的查询字符串,转换为批量查询条件
    makeQueryArgs : function(query){
        var result = {
            filter: {}
        };

        if(query){
            for(var k in query){
                if(k === 'sortBy') result.sortBy = query[k];
                else if(k === 'pageSize') result.pageSize = Number(query[k]);
                else if(k === 'nextMarker') result.nextMarker = Number(query[k]);
                else{
                    if(query[k] === "null") // null被解释为特别含义
                        result.filter[k] = null;
                    else
                        result.filter[k] = this.parseRegExp(query[k]);
                }
            }
        }

        return result;
    },
    // 重试包装
    retryWrapG: function*(nMaxRetry, fnG, shouldRetryFn){
        if(!shouldRetryFn)
            shouldRetryFn = function(){ return true; };

        var nRetried = 0;
        while(true){
            try {
                return yield fnG;
            }
            catch (ex) {
                if (shouldRetryFn(ex) && nRetried < nMaxRetry)
                    nRetried++;
                else
                    throw ex;
            }
        }
    }
};
