var child_process = require('child_process');
var fs = require("fs");
var config = require("./config")
var os = require('os');
var ifaces = os.networkInterfaces();

/**
 * https://github.com/javascript-obfuscator/javascript-obfuscator#deadcodeinjection
 * */

var JavaScriptObfuscator = require('javascript-obfuscator');

function getIp() {
    var keys = Object.keys(ifaces);
    var alias = 0;
    var ip = null;
    for(var k in keys) {
        var iface = keys[k];
        if ('IPv4' !== iface.family || iface.internal !== false) {
            // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
            return;
        }

        if (alias >= 1) {
            // this single interface has multiple ipv4 addresses
            console.log(ifname + ':' + alias, iface.address);
        } else {
            // this interface has only one ipv4 adress
            console.log(ifname, iface.address);
            if (ip == null) ip = iface.address;
        }
        ++alias;
    }
    return ip;
}
//删除出去cordova系统文件的其他历史资源
function removeHistory(platform, theFolder) {
    if(platform == "web" || platform == "fb") {
        var list = fs.readdirSync(theFolder)
        list.forEach(function(file) {
            file = theFolder + '/' + file
            var stat = fs.statSync(file)
            if (stat && stat.isDirectory()) deleteFolderRecursive(file);
            else fs.unlinkSync(file);
        })
    } else if(platform == "wechat") {
        try{
            fs.unlinkSync(theFolder + "/" + config.outJsName);
        } catch(e) {

        }
        try{
            fs.unlinkSync(theFolder + "/" + config.outZipJsName);
        } catch(e) {

        }
    } else {
        var list = fs.readdirSync(theFolder)
        list.forEach(function(file) {
            if(config.cordovaFiles.indexOf(file) != -1) return;
            file = theFolder + '/' + file
            var stat = fs.statSync(file)
            if (stat && stat.isDirectory()) deleteFolderRecursive(file);
            else fs.unlinkSync(file);
        })
    }
}

//删除文件夹
function deleteFolderRecursive(path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function(file) {
            var curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        try{
            fs.rmdirSync(path);
        } catch(e) {
            //console.log(e);
        }
    }
};

/*
 * 复制目录、子目录，及其中的文件
 * @param src {String} 要复制的目录
 * @param dist {String} 复制到目标目录
 */
function copyDir(src, dist, callback) {
    try{
        // 目录不存在时创建目录
        fs.mkdirSync(dist);
    } catch(e) {

    }

    _copy(null, src, dist);

    function _copy(err, src, dist) {
        if (err) {
            callback(err);
        } else {
            var paths = fs.readdirSync(src);

            paths.forEach(function(path) {
                if(path.indexOf(".") == 0) return;
                var _src = src + '/' + path;
                var _dist = dist + '/' + path;
                var stat = fs.statSync(_src);
                // 判断是文件还是目录
                if (stat.isFile()) {
                    fs.writeFileSync(_dist, fs.readFileSync(_src));
                } else if (stat.isDirectory()) {
                    // 当是目录是，递归复制
                    copyDir(_src, _dist, callback)
                }
            })
        }
    }
}

function googleCompile(outputJs, publishFolder, callback) {

    var jsList = outputJs;
    outputJs = publishFolder + "/" + config.outZipJsName;

    //压缩等级
    var compileLevel = "SIMPLE_OPTIMIZATIONS"; //[WHITESPACE_ONLY | SIMPLE_OPTIMIZATIONS | ADVANCED_OPTIMIZATIONS]
    //--create_source_map ' + (publishFolder + '/main.min.js.map')
    var cmdStr = 'java -jar ' + __dirname + '/compiler-1.6.jar' + ' --language_in=ECMASCRIPT5 --warning_level=quiet  --debug=false ' + ' --compilation_level ' + compileLevel + ' --js_output_file ' + outputJs + " " + jsList;

    console.log(cmdStr);

    var exec = child_process.exec(cmdStr);

    exec.stdout.on('data', function(info) {
        if (info.length > 1) console.log(info);
    });
    exec.stderr.on('data', function(err) {
        if (err.length > 1) console.log(err);
        process.exit();

    });
    exec.on('exit', function(code) {

        console.log("--------google compile over--------");

        if(!config.obscure) {
            fs.unlinkSync(publishFolder + "/" + config.outJsName);
            if(callback) callback();
        } else {
            //var wechatMainFile = publishFolder + "/" + wechatFile;
            //var fileStr = fs.readFileSync(wechatMainFile, "utf8");
            //fileStr = fileStr.replace("require('gameCore')", "require('gameCore.min')")
            //fs.writeFileSync(wechatMainFile, fileStr);

            var fileStr = fs.readFileSync(outputJs, "utf8");

            var jsStr = "";

            //if(isLib) {
            //    googleCompile(false, fileStr);
            //} else
            {
                //if(lockedDomain) {
                //    var lockScript = '$(function(){' +
                //        'if(document.domain.indexOf("'
                //        + lockedDomain
                //        + '") == -1) ' +
                //        '{'  +
                //        '$("body").empty();' +
                //        '}' +
                //        '}' +
                //        ')'
                //
                //    //锁定域名
                //    fileStr = fileStr + lockScript;
                //}
                //if(onlyMobile) {
                //    //TODO
                //    var onlyMobileScript =
                //    'window.mobileAndTabletcheck = function() {' +
                //     +'var check = false;' +
                //     +'(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);'
                //     +'   return check;'
                //    +'};' +
                //    'if(!mobileAndTabletcheck()){alert("fuck")}';
                //    console.log(onlyMobileScript);
                //    fileStr = fileStr + onlyMobileScript;
                //}

                fileStr = obfuscation(fileStr);
                fs.writeFileSync(outputJs, jsStr + fileStr);
                if(callback) callback();
            }
        }
    });
}

function cocosCompile(callback, release) {

    //var cmdStr = "cocos compile -p web -m release --advanced --source-map";
    var cmdStr = "cocos compile -p web";
    if(release === true) cmdStr += " -m release"

    console.log(cmdStr);

    var exec = child_process.exec(cmdStr);

    exec.stdout.on('data', function(info) {
        if (info.length > 1) console.log(info);
    });
    exec.stderr.on('data', function(err) {
        if (err.length > 1) console.log(err);
        process.exit();

    });
    exec.on('exit', function(code) {

        console.log("--------cocos compile over--------");
        if(callback) callback();
    });
}

function obfuscation(jsStr) {
    var options = {
        compact: true,

        //设为true，threshHold是0-1，越大文件越大，效率越低
        controlFlowFlattening: true,
        controlFlowFlatteningThreshold: 0.75,

        //设为true，注入垃圾代码，threshHold是0-1，越大文件越大，效率越低
        deadCodeInjection: true,
        deadCodeInjectionThreshold: 0.75,

        //禁止本地编译
        debugProtection: true,
        debugProtectionInterval: true,
        disableConsoleOutput: true,

        identifierNamesGenerator: 'hexadecimal',
        log: false,
        renameGlobals: false,
        rotateStringArray: true,
        //放置代码被格式化，貌似用处不大
        selfDefending: true,

        //导致页面解析变慢
        //rc4比base64还慢, 文件略大, 769k到967K
        //测试文件分别是base64, rc4, 都不要， selfdefending为false
        //文件大小769, 967, 671,670，事实证明，不要stringArray的话，全是明码，对比下rc4和base64好了
        stringArray: true,
        stringArrayEncoding: "rc4", //"rc4",//'rc4' or base64
        stringArrayThreshold: 0.75,

        transformObjectKeys: true,
        unicodeEscapeSequence: false
    }

    var obfuscationResult = JavaScriptObfuscator.obfuscate(jsStr, options);
    return obfuscationResult.getObfuscatedCode();
}

function handleWechat(mainStr) {
    //修正pixi的export的问题
    mainStr = mainStr.replace(/typeof global !== "undefined" \? global : typeof self !== "undefined" \? self : typeof window !== "undefined" \? window : \{\}/g, 'window');
    //修正matter的export的问题
    mainStr = mainStr.replace(/if\(typeof exports==="object"&&typeof module!=="undefined"\)\{module.exports=f\(\)\}else if\(typeof define==="function"&&define.amd\)\{define\(\[\],f\)\}else/g, '');
    //修正decomp.js的export的问题
    mainStr = mainStr.replace(/if\("object"==typeof exports&&"undefined"!=typeof module\)module.exports=e\(\);else if\("function"==typeof define&&define.amd\)define\(\[\],e\);else/g, "");
    //修正pixi的filter的export的问题
    mainStr = mainStr.replace(/"object"==typeof exports&&"undefined"!=typeof module\?t\(exports,require\("@tools\/fragments"\),require\("pixi.js"\)\):"function"==typeof define&&define\.amd\?define\(\["exports","@tools\/fragments","pixi.js"\],t\):/g, "");
    //修正pixi的particle的export的问题
    mainStr = mainStr.replace(/if\(typeof exports==="object"&&typeof module!=="undefined"\)\{module.exports=f\(\)}else if\(typeof define==="function"&&define.amd\)\{define\(\[\],f\)\}else/g, "");

    return mainStr;
}

function handleWechatMainFile(zipped) {
    var wechatMainFile = config.publishFolder("wechat") + "/" + config.wechatMain;
    var fileStr = fs.readFileSync(wechatMainFile, "utf8");
    var outJsName = config.outJsName.replace(".js", "");
    var outZipJsName = config.outZipJsName.replace(".js", "");
    if(zipped) fileStr = fileStr.replace("require('" + outJsName + "')", "require('" + outZipJsName + "')");
    else fileStr = fileStr.replace("require('" + outZipJsName + "')", "require('" + outJsName + "')");
    fs.writeFileSync(wechatMainFile, fileStr);
}

//将ios或android分别发布一个web版本，上传服务器后可远程加载，避免更新
function generateNativeWeb(platform, callback) {
    var pRoot = config.publishRoot;
    var sourceFolder = config.publishFolder(platform);
    var nWebFolder = pRoot + "/" + platform + "_web";

    //清除历史，
    if(fs.existsSync(nWebFolder)) {
        deleteFolderRecursive(nWebFolder);
    }
    fs.mkdirSync(nWebFolder);

    //拷贝过去
    copyDir(sourceFolder, nWebFolder);

    //删掉httpd.js
    var httpdFile = nWebFolder + "/httpd.js";
    if(fs.existsSync(httpdFile)) {
        fs.unlinkSync(httpdFile);
    }

    //去掉index.html里面对http.js的引用
    var indexHtml = nWebFolder + "/index.html";
    var indexStr = fs.readFileSync(indexHtml, "utf8");
    indexStr = indexStr.replace('<script type="text/javascript" src="httpd.js"></script>', "");
    fs.writeFileSync(indexHtml, indexStr);

    //上传服务器
    if(config.compileOptions.host) {
        var cmdStr = "scp -rv " + nWebFolder + "/* root@" + config.compileOptions.host + ":/var/www/html/" + config.compileOptions.hostPath
        var exec = child_process.exec(cmdStr);

        console.log(cmdStr);

        exec.stdout.on('data', function(info) {
            if (info.length > 1) console.log(info);
        });
        exec.stderr.on('data', function(err) {
            if (err.length > 1) console.log(err);
            process.exit();

        });
        exec.on('exit', function(code) {
            if(callback) callback();
        });
    } else {
        if(callback) callback();
    }
}

//将ios或android分别发布一个sehll版本，直接加载远程地址
function generateNativeShell(platform, callback) {
    var pRoot = config.publishRoot;
    var sourceRootFolder = config.publishFolderRoot(platform);
    var realPlat = platform + "_shell";
    var wwwFolder = config.publishFolder(realPlat);
    var shellFolder = pRoot + "/" + realPlat;

    //清除历史，
    if(fs.existsSync(shellFolder)) {
        deleteFolderRecursive(shellFolder);
    }
    try{
        fs.mkdirSync(shellFolder);
    }catch(e){

    }

    //拷贝过去
    copyDir(sourceRootFolder, shellFolder);

    //删除不相干文件
    removeHistory(platform, wwwFolder);
    //删掉httpd.js
    var httpdFile = wwwFolder + "/httpd.js";
    if(fs.existsSync(httpdFile)) {
        fs.unlinkSync(httpdFile);
    }
    var myCordovaFile = wwwFolder + "/MyCordova.js";
    if(fs.existsSync(myCordovaFile)) {
        fs.unlinkSync(myCordovaFile);
    }
    //去掉index.html里面对http.js的引用
    var indexHtml = wwwFolder + "/index.html";
    fs.unlinkSync(indexHtml);
    indexHtml = wwwFolder + "/index1.html";
    fs.unlinkSync(indexHtml);

    //更改index的远程地址
    // <content src="index.html" />
    var configXml = shellFolder + "/" + config.compileOptions.pureGameId + "/config.xml";
    var configStr = fs.readFileSync(configXml, "utf8");
    configStr = configStr.replace('<content src="index.html" />', '<content src="' + config.compileOptions.defaultEntry + '" />');
    fs.writeFileSync(configXml, configStr);

    if(callback) callback();
}

//将ios或android分别发布一个sehll版本，从masterServer上获取游戏地址，然后加载
function generateNativeShell1(platform, callback) {
    var pRoot = config.publishRoot;
    var sourceRootFolder = config.publishFolderRoot(platform);
    var realPlat = platform + "_shell1";
    var wwwFolder = config.publishFolder(realPlat);
    var shellFolder = pRoot + "/" + realPlat;

    //清除历史，
    if(fs.existsSync(shellFolder)) {
        deleteFolderRecursive(shellFolder);
    }
    fs.mkdirSync(shellFolder);

    //拷贝过去
    copyDir(sourceRootFolder, shellFolder);

    //删除不相干文件
    removeHistory(platform, wwwFolder);
    //删掉httpd.js
    var httpdFile = wwwFolder + "/httpd.js";
    if(fs.existsSync(httpdFile)) {
        fs.unlinkSync(httpdFile);
    }
    var myCordovaFile = wwwFolder + "/MyCordova.js";
    if(fs.existsSync(myCordovaFile)) {
        fs.unlinkSync(myCordovaFile);
    }
    //去掉index.html里面对http.js的引用
    var indexHtml = wwwFolder + "/index1.html";
    var indexStr = fs.readFileSync(indexHtml, "utf8");
    fs.unlinkSync(indexHtml);

    //var masterUrl = "$master$";
    //var gameId = "$gameId$";
    //var defaultUrl = "$url$";
    indexStr = indexStr.replace("$master$", config.compileOptions.entryMaster);
    indexStr = indexStr.replace("$gameId$", config.compileOptions.gameId);
    indexStr = indexStr.replace("$url$", config.compileOptions.defaultEntry);

    fs.writeFileSync(wwwFolder + "/index.html", indexStr);

    if(callback) callback();
}

function parseArgs() {
    var argv = process.argv.slice(2);
    var args = {};
    var key = null;
    for(var i = 0; i < argv.length; i++) {
        var arg = argv[i];
        var flagIndex = arg.indexOf("-");
        if(flagIndex == 0) {
            key = arg.slice(1, arg.length);
        } else if(key != null) {
            if(arg === "true") arg = true;
            if(arg === "false") arg = false;
            args[key] = arg;
        }
    }
    return args;
}

/**
 * Get game url in appstroe with apple id and country provided
 * */
function getGameUrl(platform, appId, country) {
    if(platform == "ios") {
        if(!country) country = "cn";
        return "https://itunes.apple.com/" + country + "/app/id" + appId
    }
    //TODO,others
}

module.exports = {
    deleteFolderRecursive: deleteFolderRecursive,
    copyDir: copyDir,
    googleCompile: googleCompile,
    cocosCompile: cocosCompile,
    getIp: getIp,
    handleWechat: handleWechat,
    handleWechatMainFile: handleWechatMainFile,
    generateNativeShell: generateNativeShell,
    generateNativeWeb: generateNativeWeb,
    removeHistory: removeHistory,
    parseArgs: parseArgs,
    getGameUrl: getGameUrl
}