/**
 * Created by long on 18/6/28.
 */
var fs = require("fs");
var util = require("./util")
var config = require("./config")
var path = require("path");
var request = require("request");
var Jimp = require('jimp');

var sourceFolders = ["src", "res"];

function overCompile(platform, mainJs, cb) {
    var publishFolder = config.publishFolder(platform);
    if(platform == "ios" || platform == "android") {
        if(config.outputShell) {
            util.generateNativeShell(platform, function() {
                util.generateNativeWeb(platform, function() {
                    console.log("-----over------");
                    if(cb) cb();
                });
            })
        } else {
            try{
                fs.unlinkSync(publishFolder + "/index1.html");
            } catch(e) {

            }
            console.log("-----over------");
            if(cb) cb();
        }
    } else if(platform == "fb"){
        base64ShareImg(mainJs, true, cb);
    } else if(platform == "wechat") {
        try{
            fs.unlinkSync(publishFolder + "/index.html");
            fs.unlinkSync(publishFolder + "/build.xml");
        } catch(e) {

        }
        console.log("-----over------");
        if(cb) cb();
    } else {
        console.log("-----over------");
        if(cb) cb();
    }
}

function base64ShareImg(mainJs, exit, cb) {
    //将分享图片转为base64
    if(config.flaxConfig && config.flaxConfig.shareImg) {
        var filename = config.flaxConfig.shareImg;
        if(filename.indexOf("http") > -1) {
            var localFileName = filename.lastIndexOf("/");
            localFileName = filename.substring(localFileName + 1);
            request(filename).pipe(fs.createWriteStream(localFileName)).on('close', function(){
                convertShareImg(localFileName, true, mainJs, function(err, code) {
                    if(cb) cb();
                    if(exit === true) {
                        console.log("-----over------");
                        process.exit(0);
                    }
                })
            });
        } else {
            convertShareImg(path.join(config.sourceFolder(), filename), false, mainJs, function(err, code) {
                if(cb) cb();
                if(exit === true) {
                    console.log("-----over------");
                    process.exit(0);
                }
            });
        }
    } else {
        if(cb) cb();
        if(exit === true) {
            console.log("-----over------");
            process.exit(0);
        }
    }
}

function convertShareImg(shareImg, remove, mainJs, cb) {
    //远程地址？
    if(fs.existsSync(shareImg)){
        Jimp.read(shareImg).then(function(img) {
            img.getBase64(img.getMIME(), function(err, code) {
                if(remove === true) {
                    fs.unlinkSync(shareImg);
                }
                if(!err && code) {
                    var mainStr = fs.readFileSync(mainJs, "utf8");
                    if(mainJs.indexOf(".json") > -1) {
                        mainStr = JSON.parse(mainStr);
                        mainStr.shareImg = code;
                        fs.writeFileSync(mainJs, JSON.stringify(mainStr));
                    } else {
                        mainStr += "flax.game.config.shareImg='" + code + "'";
                        fs.writeFileSync(mainJs, mainStr);
                    }
                }
                cb(err, code);
            })
        });
    }
}

module.exports = function(platform, cb) {

    var boostFile = "src/flax/Boost.js";

    var singleFile = config.compileOptions.singleFile;
    var zipFile = config.compileOptions.zipFile;
    var publishFolder = config.publishFolder(platform);
    var sourceFolder = config.sourceFolder();

    var projectJson = JSON.parse(fs.readFileSync(sourceFolder + "/project.json", "utf8"));
    var jsModules = projectJson.modules;
    var jsList = projectJson.jsList;

    projectJson.platform = platform;
    //平台配置参数
    projectJson.platformConfig = config.platformConfig;
    if(platform == "fb") projectJson.language = "en";

    var copyRes = true;
    var indexFile = null;
    if(platform != "wechat") {
        if(platform == "web" || platform == "fb") {
            indexFile = fs.readFileSync(sourceFolder + "/index.html", "utf8");
        } else {
            projectJson.cordova = true;
            indexFile = fs.readFileSync(publishFolder + "/index.html", "utf8");
        }
    } else {
        singleFile = true;
        copyRes = false;
        //资源地址，TODO
        //projectJson.resUrl = "http://" + ip + ":8888/";
        projectJson.resUrl = config.resUrl;
        //是否微信小游戏
        projectJson.wx = true;
        //不显示FPS
        projectJson.showFPS = false;
    }

    if(config.isCocos) {
        singleFile = true;
        zipFile = true;
    }

    //如果是原始工程，则src, res等直接拷贝过去
    if(!singleFile) {
        for (var i = 0; i < sourceFolders.length; i++) {
            util.copyDir(sourceFolder + "/" + sourceFolders[i], publishFolder + "/" + sourceFolders[i]);
        }
        fs.writeFileSync(publishFolder + "/project.json", JSON.stringify(projectJson));

        var mainStr = fs.readFileSync(sourceFolder + "/main.js", "utf8");

        fs.writeFileSync(publishFolder + "/main.js", mainStr);

        if(indexFile) {
            indexFile = indexFile.replace(config.outJsName, boostFile);
            indexFile = indexFile.replace(config.outZipJsName, boostFile);
            if(platform == "fb") {
                if(indexFile.indexOf("/fbinstant.") == -1) {
                    indexFile = indexFile.replace("</head>", '<script src="' + config.fbsdk + '"></script></head>');
                }
            }
            fs.writeFileSync(publishFolder + "/index.html", indexFile);
        }

        if(platform == "fb") base64ShareImg(publishFolder + "/project.json", false, cb);
        else if(cb) cb();

    } else if(!config.isCocos){

        if(copyRes !== false) util.copyDir(sourceFolder + "/res", publishFolder + "/res");

        projectJson.jsList = [];

        var appid = config.platformConfig.appid || config.flaxConfig.appleId;
        var gameUrl = util.getGameUrl(platform, appid);
        if(gameUrl) projectJson.shareUrl = gameUrl;

        if(indexFile) {
            var outputJsName = zipFile ? config.outZipJsName : config.outJsName;
            indexFile = indexFile.replace(boostFile, outputJsName);
            if(zipFile) indexFile = indexFile.replace(config.outJsName, config.outZipJsName);
            else indexFile = indexFile.replace(config.outZipJsName, config.outJsName);

            if(platform == "fb") {
                if(indexFile.indexOf("/fbinstant.") == -1) {
                    indexFile = indexFile.replace("</head>", '<script src="' + config.fbsdk + '"></script></head>');
                }
            }
            fs.writeFileSync(publishFolder + "/index.html", indexFile);
        }

        var flaxDir = sourceFolder + "/src/flax";

        var mainStr = "";
        var loadJsList = function(urls, isFlax) {
            for (var i = 0; i < urls.length; i++) {
                var url = urls[i];
                //只有web下打包loaidng.js进去
                if(platform != "web" && url == "loading.js") {
                    continue;
                }
                url = flaxDir + "/" + url;
                if (!isFlax) url = sourceFolder + "/" + urls[i];
                mainStr += fs.readFileSync(url, "utf8") + "\n";
            }
        }


        var moduleConfig = JSON.parse(fs.readFileSync(flaxDir + "/" + "moduleConfig.json", "utf8"));

        var engineName = "pixi";

        for (var i = 0; i < jsModules.length; i++) {
            var moduleName = jsModules[i];
            var module = moduleConfig['modules'][moduleName];
            if (module) {
                if (module['base']) loadJsList(module['base'], true);
                if (module[engineName + "_base"]) loadJsList(module[engineName + "_base"], true);
                if (module['common']) loadJsList(module['common'], true);
                if (module[engineName]) loadJsList(module[engineName], true);
            }
        }

        loadJsList(jsList);
        mainStr += "flax.game.config=" + JSON.stringify(projectJson) + ";";
        loadJsList(['main.js']);

        if(platform == "wechat") {
            util.handleWechatMainFile(zipFile);
            mainStr = util.handleWechat(mainStr);
        }

        var outputJs = publishFolder + "/" + config.outJsName;
        var outputZipJs = publishFolder + "/" + config.outZipJsName;
        fs.writeFileSync(outputJs, mainStr);

        if(!zipFile) {
            overCompile(platform, outputJs, cb);
        } else {
            util.googleCompile(outputJs, publishFolder, function() {
                overCompile(platform, outputZipJs, cb);
            });
        }
    } else {

        util.cocosCompile(function(){

            var outputJsName = zipFile ? config.outZipJsName : config.outJsName;

            var outputZipJs = publishFolder + "/" + outputJsName;

            var cocosPublishFolder = path.join(process.cwd(), "publish/html5");
            util.copyDir(cocosPublishFolder, publishFolder);
            util.deleteFolderRecursive(cocosPublishFolder);

            var mainJsFile = path.join(publishFolder, "game.min.js");
            fs.writeFileSync(outputZipJs, fs.readFileSync(mainJsFile));
            fs.unlinkSync(mainJsFile);

            if(indexFile) {
                indexFile = indexFile.replace('<script src="main.js"></script>', "");
                if(platform == "web") boostFile = "frameworks/cocos2d-html5/CCBoot.js";
                indexFile = indexFile.replace(boostFile, outputJsName);
                if(platform == "fb") {
                    if(indexFile.indexOf("/fbinstant.") == -1) {
                        indexFile = indexFile.replace("</head>", '<script src="' + config.fbsdk + '"></script></head>');
                    }
                }
                if(indexFile.indexOf('gameCanvas') == -1) {
                    indexFile = indexFile.replace("<body>", '<body><canvas id="gameCanvas" width="750" height="1334"></canvas>');
                }
                fs.writeFileSync(publishFolder + "/index.html", indexFile);
            }

            //更新project.json
            var projectJson = fs.readFileSync(publishFolder + "/project.json", "utf8");
            projectJson = JSON.parse(projectJson);
            projectJson.platform = platform;
            var appid = config.platformConfig.appid || config.flaxConfig.appleId;
            var gameUrl = util.getGameUrl(platform, appid);
            if(gameUrl) projectJson.shareUrl = gameUrl;
            fs.writeFileSync(publishFolder + "/project.json", JSON.stringify(projectJson));

            if(platform == "wechat") {
                util.handleWechatMainFile(zipFile);
            }
            overCompile(platform, outputZipJs, cb)
        }, zipFile)
    }
}