var fs = require('fs'),
    vm = require('vm'),
    qs = require('querystring'),
    url = require('url'),
    path = require('path'),
    utils = require('./utils.js'),
    mockjs = require('mockjs');

function MockData(opt){
    opt = utils.extend(true, {
        datapath: path.join(process.cwd() + "mock/"),
        mockrc: ".mockrc", //相对mock datapath
        ignore: ['html', 'js', 'css', 'jpg', 'png', 'gif'],
        regexurl: { //前面是regex new RegExp()
        }
    }, opt);

    this.init(opt);
}

MockData.prototype = {
    init: function(opt){
        this.ignore = opt.ignore;
        this.mockItems = this.convertRegexURL(opt.datapath, opt.regexurl);
        this.initMockRandom(path.isAbsolute(opt.mockrc)? opt.mockrc : path.join(opt.datapath, opt.mockrc));
    },
    initMockRandom: function(mockrcpath){
        console.log("-------mockrcpath:\n", mockrcpath)
        var mockRandom = fs.existsSync(mockrcpath) ? 
                            JSON.parse(fs.readFileSync(mockrcpath)) : {};

        for(var i in mockRandom){
            var randomData = {}, 
                name = i.toLowerCase(), 
                list = name + 's';
            (function(i, list, name){
                randomData[list] = mockRandom[i];
                randomData[name] = function(data){
                    return this.pick(this[list]);
                }
                console.log(randomData);
                mockjs.Random.extend(randomData);
                console.log("-------Random add:\n", randomData)
            })(i, list, name);
        }
    },
    convertRegexURL: function(mockPath, regexurl){
        var mockItems = {}, j = 0;
        for(var i in regexurl){
            mockItems[j++] = {
                reg: new RegExp(i),
                data: path.join(mockPath, regexurl[i]) 
            }
        }
        return mockItems;
    },
    // @parma url:当前请求的url, 
    // @parma ext:当前请求的后缀，用于过滤一些不需要mock的文件
    // @return {cnt, ext} cnt:mock数据文件的原始内容, ext: mock类型
    getMockData: function(url, ext){
        var cnt, type, mockItems = this.mockItems;
        if(this.ignore.indexOf(ext) === -1){
            for(var i in mockItems){
                var item = mockItems[i];
                if(item.reg.test(url)){
                    cnt = fs.readFileSync(item.data);
                    type = path.extname(item.data).slice(1);
                    break;
                }
            }
        }
        return {cnt: cnt, type: type};
    },
    getMockJsonData: function(json){
        return mockjs.mock(json);
    },
    // mock response 用mock data 响应服务
    mockResponse: function(data, req, res, config){
        if(!data.cnt) return false;
        // console.log("----------ajax json:\n", data.type);
        switch(data.type){
            case 'mjson': //处理mockjson
                console.log(mockjs.mock(JSON.parse(data.cnt)))
                data.cnt = JSON.stringify(mockjs.mock(JSON.parse(data.cnt)), null, 4);
            case 'json':
                res.writeHead(200, {
                    'Content-Type': utils.MIME['json']
                });
                res.write(data.cnt);
                res.end();
                break;
            case 'js':
                //data = new vm.script(data[0]);
                // 将分解好的url给mock用户*.js
                req.wwwurl = url.parse(config.protocol + '://' + req.headers.host + req.url);
                req.wwwurl.queryObj = req.wwwurl.query ? qs.parse(req.wwwurl.query) : {};
                //extname === 'html' && console.log(req, '\n\n\n\n', req.wwwurl)
                console.log('----------mock js func:\n', data.cnt.toString());
                vm.runInThisContext('(' + data.cnt + ')')(req, res);
                break;
            default:
                console.log("mock 暂只支持.mjson .json .js文件");
                res.end("mock 暂只支持.mjson .json .js文件");
        }
        return true;
    }

}


module.exports = MockData;
@@ -2722,24 +2722,41 @@
 data.type);%0A
+        try%7B%0A    
         swit
@@ -2766,24 +2766,28 @@
 data.type)%7B%0A
+    
             
@@ -2821,32 +2821,36 @@
                 
+  
+  
 console.log(mock
@@ -2880,16 +2880,20 @@
 .cnt)))%0A
+    
         
@@ -2975,32 +2975,36 @@
 4);%0A            
+    
 case 'json':%0A   
@@ -3008,32 +3008,36 @@
                 
+  
+  
 res.writeHead(20
@@ -3037,24 +3037,28 @@
 Head(200, %7B%0A
+    
             
@@ -3116,16 +3116,20 @@
         
+    
 %7D);%0A    
@@ -3132,32 +3132,36 @@
                 
+ 
+   
 res.write(data.c
@@ -3165,16 +3165,20 @@
 a.cnt);%0A
+    
         
@@ -3204,32 +3204,36 @@
                 
+    
 break;%0A         
@@ -3227,32 +3227,36 @@
 ak;%0A            
+ 
+   
 case 'js':%0A     
@@ -3250,16 +3250,20 @@
 e 'js':%0A
+    
         
@@ -3299,24 +3299,28 @@
 t(data%5B0%5D);%0A
+    
             
@@ -3354,32 +3354,36 @@
                 
+    
 req.wwwurl = url
@@ -3452,32 +3452,36 @@
                 
+    
 req.wwwurl.query
@@ -3538,16 +3538,20 @@
 ) : %7B%7D;%0A
+    
         
@@ -3631,32 +3631,36 @@
                 
+    
 console.log('---
@@ -3722,16 +3722,20 @@
         
+    
 vm.runIn
@@ -3787,39 +3787,47 @@
                 
+   
+ 
 break;%0A
+    
             defa
@@ -3831,16 +3831,20 @@
 efault:%0A
+    
         
@@ -3903,32 +3903,36 @@
                 
+   
+ 
 res.end(%22mock %E6%9A%82%E5%8F%AA
@@ -3947,32 +3947,110 @@
  .json .js%E6%96%87%E4%BB%B6%22);%0A
+            %7D%0A        %7D catch(e)%7B%0A            console.log(%22mock error: %22, e);%0A
         %7D%0A      

fix mock error