var fs = require("fs");
var os = require('os'),
    clui = require('clui');
var log = require('single-line-log').stdout;

var util = require("./src/util")
var config = require("./src/config");

var flaxCompile = require("./src/flax_compile");
var htmlCompile = require("./src/html_compile");
var updateXcodeProj = require("./src/updateXcodeProj");

var Progress = clui.Progress;
var thisProgressBar = new Progress(20);

var path = require("path");
var request = require("request");
var progress = require('request-progress');
var unzip = require("unzip");
var Jimp = require('jimp');

var copySplashes = require("./src/copySplashes")
var genIcons = require("./src/genIcons")

function initConfig() {
    var gameId = config.compileOptions.gameId;
    var platform = config.compileOptions.platform;
    //初始化参数
    var sFolder = process.cwd();
    var projectJson = sFolder + "/project.json";
    var hasProjJson = true;
    if (!fs.existsSync(projectJson)) {
        projectJson = sFolder + "/www/project.json";
        if (!fs.existsSync(projectJson)) {
            hasProjJson = false;
        }
    }
    if (hasProjJson) {
        try {
            var jsonStr = fs.readFileSync(projectJson, "utf8");
            var json = config.flaxConfig = JSON.parse(jsonStr);
            if (json.gameId) gameId = config.compileOptions.gameId = json.gameId;
            else throw "请在project.json中定义gameId字段，一般为com.domain.gameId字样，也就是游戏的包名";

            if (json.name) config.compileOptions.gameName = json.name;
            if (json.name_en) config.compileOptions.gameName_en = json.name_en;

            //平台配置参数
            var platformJsonFile = path.join(config.sourceFolder(), "platform.json");
            if (fs.existsSync(platformJsonFile)) {
                var platformJson = fs.readFileSync(platformJsonFile, "utf8");
                platformJson = JSON.parse(platformJson);
                if (platformJson[platform]) {
                    config.platformConfig = platformJson[platform];
                }
            }
            if (platform == "wechat") {
                if (json.wechat && json.wechat.resUrl) config.resUrl = json.wechat.resUrl;
                else if (config.platformConfig.resUrl) config.resUrl = config.platformConfig.resUrl;
            } else if (platform == "fb") {
                if (json.fb && json.fb.sdk) config.fbsdk = json.fb.sdk;
                else if (config.platformConfig.fbsdk) config.fbsdk = config.platformConfig.fbsdk;
            }

            //每次发布都自动更新version
            var oldVersion = json.version;
            var newVersion = parseFloat(oldVersion) + 0.001;
            newVersion = parseFloat(newVersion.toFixed(3));
            jsonStr = jsonStr.replace(oldVersion, newVersion);
            fs.writeFileSync(projectJson, jsonStr);

        } catch (e) {
            console.log(e);
        }
    }
    var pureId = gameId.split(".");
    pureId = pureId[pureId.length - 1];
    config.compileOptions.pureGameId = pureId;
    config.compileOptions.hostPath = config.compileOptions.hostPath.replace("$", pureId);
    config.compileOptions.defaultEntry = config.compileOptions.defaultEntry.replace("$", pureId);

    if (platform == "fb" || platform == "wechat") {
        //拷贝排行榜资源到res目录
        copyLeaderBoardRes();
    }
}

function copyLeaderBoardRes() {
    // var sFile = __dirname + "/templates/res/leaderboard.json";
    var tFile = config.sourceFolder() + "/res/leaderboard.json";
    if (!fs.existsSync(tFile)) {
        // fs.writeFileSync(tFile, fs.readFileSync(sFile));
        util.copyDir(__dirname + "/templates/res", config.sourceFolder() + "/res");
    }
    tFile = config.sourceFolder() + "/flash/leaderboard.fla";
    if (!fs.existsSync(tFile)) {
        util.copyDir(__dirname + "/templates/flash", config.sourceFolder() + "/flash");
    }
}

function doCompile() {

    var platform = config.compileOptions.platform;
    var publishFolder = config.publishFolder(platform);
    //删除历史资源
    util.removeHistory(platform, publishFolder);

    flaxCompile(platform, function() {
        if (platform == "ios") {
            //更改包名
            updateXcodeProj(config.compileOptions.pureGameId);
            //拷贝闪屏过去
            copySplashes();
            //尝试生成icon
            genIcons();
        }
    });
    //if(config.compileOptions.isFlax) flaxCompile(platform);
    //else htmlCompile(platform);
}

function unzipTemplate(targetZip) {
    console.log("正在解压: " + targetZip);

    fs.createReadStream(targetZip)
        .pipe(unzip.Extract({ path: config.publishRoot }))
        .on("close", function() {

            fs.unlinkSync(targetZip);

            var sourcePath = config.publishRoot + "/cordovaTemplate-master/platforms/" + platform;
            util.copyDir(sourcePath, config.publishRoot + "/" + platform);
            doCompile();
            util.deleteFolderRecursive(config.publishRoot + "/cordovaTemplate-master");

        });
}

function doPublish(argv) {
    //var argv = util.parseArgs();

    console.log("--help info: ");
    console.log("-plat ios/android/web/wechat/fb: 安卓还是ios，默认是ios");
    console.log("-sin true/false: 是否将所有js打进单个文件，默认false");
    console.log("-min true/false：是否将js进行压缩处理，sin自动为true，默认false");
    console.log("-obs true/false：是否进行混淆处理，sin和min自动为true，默认false");
    console.log("-clean true/false: 是否完全重新发布，true将删除现有发布，默认false");

    console.dir("打包参数：");
    console.dir(argv);

    var platform = argv.p || "ios"; //平台
    platform = platform.toLowerCase();
    var isNative = platform == "ios" || platform == "android";
    var singleFile = argv.s; //是否单个文件
    var zipFile = argv.m; //是否压缩
    var obscure = argv.o; //是否混淆
    var forceClean = argv.c; //是否清理旧发布

    if (obscure) zipFile = singleFile = true;
    else if (zipFile) singleFile = true;

    config.compileOptions.platform = platform;
    config.compileOptions.isNative = isNative;
    config.compileOptions.singleFile = singleFile;
    config.compileOptions.zipFile = zipFile;
    config.compileOptions.obscure = obscure;
    config.compileOptions.forceClean = forceClean;

    if (argv.host && argv.hostPath) {
        config.compileOptions.host = argv.host;
        config.compileOptions.hostPath = argv.hostPath;
    }

    if (!fs.existsSync(config.publishRoot)) {
        fs.mkdirSync(config.publishRoot);
    }

    var publishFolder = config.publishFolderRoot(platform);

    if (forceClean && platform != "wechat") {
        util.deleteFolderRecursive(publishFolder);
    }

    publishFolder = config.publishFolder(platform);

    initConfig();

    config.isCocos = config.flaxConfig.frameWork == "cocos" || config.flaxConfig.modules.indexOf("cocos2d") > -1;

    if (!fs.existsSync(publishFolder)) {

        if (platform == "web" || platform == "fb") {
            fs.mkdirSync(publishFolder);
            doCompile();
        } else if (platform == "wechat") {
            if (config.isCocos) {
                util.copyDir(__dirname + "/templates/wechat_cocos", config.publishRoot + "/" + platform);
            } else {
                util.copyDir(__dirname + "/templates/wechat_pixi", config.publishRoot + "/" + platform);
            }
            doCompile();
        } else if (platform == "ios" || platform == "android") {
            var targetZip = config.publishRoot + "/cordova.zip";
            if (config.useLocalTemplate) {
                util.copyDir(config.localTemplatePath + "/" + platform, config.publishRoot + "/" + platform);
                doCompile();
            } else if (fs.existsSync(targetZip)) {
                unzipTemplate(targetZip);
            } else {
                console.log("正在下载: " + config.zipUrl);
                progress(request(config.zipUrl)).on("progress", function(p) {
                    log(thisProgressBar.update(p.size.transferred, p.size.total), (p.size.transferred / 1024 / 1024).toFixed(2) + "mb/" + (p.size.total / 1024 / 1024).toFixed(2) + "mb");
                }).pipe(fs.createWriteStream(targetZip)).on('close', function() {
                    unzipTemplate(targetZip);
                });
            }
        }
    } else {
        doCompile();
    }
}

module.exports = doPublish;