'custome defined'
let mime = require("./libs/mime")
var pathToRegExp = require('path-to-regexp');
let env = process.env.BP_ENV;
// let bpRouter = {};

// 区分项目类型，和静态文件／动态接口
//需要一个路由的缓存，这个缓存一定是它本身自己
//静态的时候，需要区分是「谁」「第几次」访问的 这个接口--用在APP的接口访问过程中
//动态文件
//更新-这里应当判断这个接口是走一般mock还是走成套的套装接口项目
// ctx.request.ip
//判断逻辑，1、如果定义了这个IP是走项目的，那么就让这个IP走项目，如果没有定义，那么就让这个手机走默认的项目
let DEFAULT_PROJECT_ID = 1;
let DEFAULT_MIME_TYPE = 1;

function requireFromString(src, filename) {
    var Module = module.constructor;
    var m = new Module();
    //默认经历过解密后的都是明文的结果
    // console.log(src)
    try {
        m._compile(`module.exports = ${src}`, filename||"");    
    } catch (error) {
        console.log(error)
    }
    return m.exports;
}


module.exports = {
    //初始化moudle_route 加载一些静态的rout规则，
    init: function () {
        // 目前只有mime_type
        this.setMimeRoutes(mime.types);
    },
    // 获取所有的routes
    getRoutes: function () {
        return {
            device_routes: this.device_routes,
            project_routes: this.project_routes
        }
    },
    getUrlRoute:function(ctx,projectRoutes){
        let item;
        Object.keys(projectRoutes).forEach(function(key){
            if( item == undefined){
                if(ctx.path.match(projectRoutes[key].re)){
                    item = projectRoutes[key]
                }
            }else{
                return false
            }
        })
        return item
    },
    getDeviceProjectRoute: function (ctx) {
        if (this.device_routes[ctx.request.ip] == undefined) {
            //返回默认项目路由
            return this.default_project_route
        } else {
            return this.project_routes[this.device_routes[ctx.request.ip]]
        }
    },
    //单个设置设备的route规则,用于更新
    setDeviceProjectRoute: function (device_route_config) {
        if (device_route_config.projects == undefined) {
            device_route_config.projects = this.default_project_route
        }
        this.device_routes[`::${device_route_config.ipv6}:${device_route_config.ipv4}`] = device_route_config
    },
    //批量设置设备的route规则
    setDeviceProjectRoutes: function (device_route_config) {
        this.device_routes = {};
        device_route_config.forEach(function (item, index) {
            this.setDeviceProjectRoute(item);
        }, this);
    },
    getProjectRoute: function (ctx) {
        if (this.project_routes[ctx.bpRouter.device_route.project_id] == undefined) {
            return this.default_project_route
        } else {
            return this.project_routes[ctx.bpRouter.device_route.project_id]
        }
    },
    removeUrlForProjectRoute:function(project_id,url_obj){
        delete this.project_routes[project_id][url_obj._id]
    },
    addUrlForProjectRoute:function(project_id,url_obj){
        this.project_routes[project_id][url_obj._id] = JSON.parse(JSON.stringify(url_obj));
        this.project_routes[project_id][url_obj._id].re = pathToRegExp(url_obj.path);
    },
    //单个设置项目的route规则,用于更新
    setProjectRoute: function (project) {
        // pathToRegExp
        this.project_routes[project._id] = {};
        project.urls.forEach(function (url) {
            this.addUrlForProjectRoute(project._id,url);
            //这里面的urls应该都是url对象
            //把URL里面的FUN灌入
        }, this);
        if (project.is_default == 1) {
            this.default_project_route = this.project_routes[project._id]
        }
    },
    //批量设置项目的route规则
    setProjectRoutes: function (project_routes) {
        this.project_routes = {};
        this.project_url_exports = {};
        this.default_project_route = {};
        project_routes.forEach(function (project, index) {
            this.setProjectRoute(project)
        }, this);
    },
    //获取当前contentType的类型
    getMimeRoute: function (content_type) {
        if (this.mime_routes[content_type] == undefined) {
            return DEFAULT_MIME_TYPE
        } else {
            return this.mime_routes[content_type]
        }
    },
    //单个设定mimeroute类型
    setMimeRoute: function (mime_types) {
        this.mime_routes[mime_types.header] = mime_types
    },
    //批量设定mimeroute类型，用于区分当前接口是动态请求还是静态资源请求的
    setMimeRoutes: function (mime_types) {
        this.mime_routes = {};
        mime_types.forEach(function (item, index) {
            this.setMimeRoute(item)
        }, this);
    },
    /**
     * 设置URL的模版--该模版需要根项目下的URL挂钩
     * @param {Array} url  具体的关系URL-id与template-id，一个URL下面对应多个templates/可以
     */
    haveTemplateKeyForDevice: function(ctx,url){
        console.log(this.device_templates)
        if(this.device_templates[url._id] && this.device_templates[url._id][ctx.request.ip]){
            return true
        }else{
            return false
        }
    },
    getUrlTemplateRoute: function(url){
        return this.resp_templates[url._id]
    },
    getUrlTemplateFunction: function (url, key) {
        //根据 key 获取 当前 URL下面的模板route
        //返回是一个 Object，里面是{key1:fun,key2:fun}
        return this.resp_templates[url._id][key]
    },
    //return Fun
    getUrlModuleFromProjectRoute:function(url){
        // console.log(this.project_url_exports[project._id])
        return this.project_url_exports[url.projects][url._id]
    },
    setUrlTemplate: function (url) {
        console.log("url project id",url.projects)
        if(!(!!!this.project_routes[url.projects] && !!!this.project_routes[url.projects][url._id])){
            this.addUrlForProjectRoute(url.projects,url);
        }

        this.resp_templates[url._id] = {};
        this.device_templates[url._id ] = {};
        if(this.project_url_exports == undefined){
            this.project_url_exports = {};
        }
        if(this.project_url_exports[url.projects] == undefined){
            this.project_url_exports[url.projects] = {}
        }
        console.log(url.projects,url._id)
        this.project_url_exports[url.projects][url._id] = requireFromString(url.fun);

        url.templates.forEach(function (template, index) {
            console.log(template.key);
            this.resp_templates[url._id][template.key] = requireFromString(template.fun);
            template.devices.forEach(function(device){
                //再同一URL中，一个设备下面有且只能指定一个Template
                this.device_templates[url._id][`::${device.ipv6}:${device.ipv4}`] =  template.key
            },this)
        }, this);
    },
    setUrlTemplates: function (urls) {
        this.resp_templates = {};
        this.device_templates = {};
        urls.forEach(function (item, index) {
            // 增加环境判断，如果是生产环境，只有relace_flg = 1的才能被加载到内存中，否则不加载／测试环境加载所有的
            if(env == "debug"){
                this.setUrlTemplate(item)
            }else{
                if(item.relace_flg == 1){
                    this.setUrlTemplate(item)
                }
            }
        }, this);
    }

    /**
     * 设备是否有指定的URL路由，来判断走什么样的脚本模版
     */



    /*
    //decode的加密规则路由
    getDecodeRoute: function (ctx){
        if(this.decode_routes[ctx.bpRouter.device_route.project_id] && this.decode_routes[ctx.bpRouter.device_route.project_id][ctx.path] != undefined){
            return this.decode_routes[ctx.bpRouter.device_route.project_id][ctx.path]
        }else{
            return false
        }
    },
    setDecodeRoute: function (uri) {
        //挂在那个项目下的，那个接口，运行的加解密类型（这个类型也是需要有一个动态配置的过程的。）
        if(this.decode_routes[uri.project_id] == undefined){
            this.decode_routes[uri.project_id] = {}
        }
        this.decode_routes[uri.project_id][uri.url] = uri.decode_params
    },
    setDecodeRoutes: function (uris) {
        uris = [
            {
                url:"/abc/def",
                project_id:0,
                decode_params:[
                    "1",
                    "2",
                    "3"
                ],
                encode_params:[
                    "1",
                    "2",
                    "3"
                ]
            }
        ]
        this.decode_routes = {};
        uris.forEach(function (item, index) {
            this.setDecodeRoute(item)
        }, this);
    },
    //encode的加密规则路由
    getEncodeRoute: function (ctx){
        if(this.encode_routes[ctx.bpRouter.device_route.project_id] && this.encode_routes[ctx.bpRouter.device_route.project_id][ctx.path] != undefined){
            return this.encode_routes[ctx.bpRouter.device_route.project_id][ctx.path]
        }else{
            return false
        }
    },
    setEncodeRoute: function (uri) {
        //挂在那个项目下的，那个接口，运行的加解密类型（这个类型也是需要有一个动态配置的过程的。）
        if(this.encode_routes[uri.project_id] == undefined){
            this.encode_routes[uri.project_id] = {}
        }
        this.encode_routes[uri.project_id][uri.url] = uri.encode_params
    },
    setEncodeRoutes: function (uris) {
        this.encode_routes = {};
        uris.forEach(function (item, index) {
            this.setEncodeRoute(item)
        }, this);
    },
    */
    //需要加入URL的具体的条件路由，
    /*
    案例：
        当，URL／数据中包含特殊内容时，ctx.requ.body = ??? ctx.path include?返回什么模版／
        当，URL中包含如果没有条件，则直接返回应有的内容
     */
    /*
    getScriptRoute: function(ctx){
        // console.log(ctx.bpRouter)
        if(ctx.bpRouter.device_route == false){
            return false
        }
        if(this.script_routes[ctx.bpRouter.device_route.project_id] && this.script_routes[ctx.bpRouter.device_route.project_id][ctx.path] != undefined){
            return this.script_routes[ctx.bpRouter.device_route.project_id][ctx.path]
        }else{
            return false
        }
    },
    setScriptRoute: function(rout){
        if(this.script_routes[rout.project_id] == undefined){
            this.script_routes[rout.project_id] = {}
        }
        this.script_routes[rout.project_id][rout.url] = rout
    },
    setScriptRoutes: function(routes){
        this.script_routes = {}
        routes.forEach(function(item, index){
            this.setScriptRoute(item);
        },this);
    }
    */
}