"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const FeishuHandler_1 = __importDefault(require("./build/handler/FeishuHandler"));
const WechatHandler_1 = __importDefault(require("./build/handler/WechatHandler"));
const PackagerAndroid_1 = __importDefault(require("./package/PackagerAndroid"));
const PackagerWeb_1 = __importDefault(require("./package/PackagerWeb"));
const FileUtils_1 = __importDefault(require("./utils/FileUtils"));
const MD5Utils_1 = __importDefault(require("./utils/MD5Utils"));
const ProcessUtils_1 = __importDefault(require("./utils/ProcessUtils"));
(() => __awaiter(void 0, void 0, void 0, function* () {
    const command = ProcessUtils_1.default.getArg('--run', value => ['package', 'begin', 'end', 'cache'].indexOf(value) >= 0);
    if (!command) {
        console.error(`command error: ${command}`);
        return;
    }
    if (command === 'cache') {
        const url = ProcessUtils_1.default.getArg('--url', value => !!value && value.startsWith('http'));
        if (!url) {
            console.error(`illegal parameter --url`);
            return;
        }
        const configCache = path_1.default.join(process.env.HOME || process.env.USERPROFILE, '.sgp', 'config', `${MD5Utils_1.default.md5(url)}.json`);
        console.log(`config cache: ${configCache}`);
        return;
    }
    const project = ProcessUtils_1.default.getArg('--project', fs_1.default.existsSync);
    if (!project) {
        console.error(`illegal parameter --project or file not exists`);
        return;
    }
    const platform = ProcessUtils_1.default.getArg('--platform', value => ['web-mobile', 'android'].indexOf(value) >= 0);
    if (!project) {
        console.error(`illegal parameter --platform`);
        return;
    }
    const isolate = ProcessUtils_1.default.haveArg('--isolate');
    const mode = ProcessUtils_1.default.getArg('--mode', value => ['dev', 'debug', 'release', 'testRelease'].indexOf(value) >= 0);
    const buildResultCacheFile = path_1.default.join(project, `build_result_${mode}.json`);
    switch (command) {
        case 'begin':
        case 'end':
            {
                const key = ProcessUtils_1.default.getArg('--key', value => !!value && !value.startsWith('--'));
                const robotKey = ProcessUtils_1.default.getArg('--robot-key', value => value && !value.startsWith('--'));
                if (!robotKey) {
                    console.error(`illegal parameter --robot-key`);
                    break;
                }
                const robotType = ProcessUtils_1.default.getArg('--robot-type', value => ['wechat', 'feishu'].indexOf(value.toLocaleLowerCase()) >= 0);
                if (!robotType) {
                    console.error(`illegal parameter --robot-type`);
                    break;
                }
                const data = [];
                data.push(`平台=${platform}`);
                mode && data.push(`环境=${mode}`);
                data.push(`引擎隔离=${isolate ? '开启' : '关闭'}`);
                if (fs_1.default.existsSync(buildResultCacheFile)) {
                    if (command === 'end') {
                        const cacheContent = fs_1.default.readFileSync(buildResultCacheFile).toString();
                        console.log(`Cache Content: ${cacheContent}`);
                        const buildResult = JSON.parse(cacheContent);
                        if (buildResult.backupTimestamp)
                            data.push(`构建备份=${buildResult.backupTimestamp}`);
                        const results = buildResult.results;
                        results.forEach(result => {
                            results.length > 1 && data.push(`**SubGame - ${result.key}**`);
                            data.push(`框架版本=${result.frameworkVersion}`);
                            data.push(`游戏版本=${result.packageVersion}`);
                            data.push(`新增文件=${result.added}`);
                            data.push(`修改文件=${result.changed}`);
                            data.push(`删除文件=${result.deleted}`);
                            if (result.size >= 0) {
                                data.push(`游戏包大小=${(result.size / 1024 / 1024).toFixed(2)}MB`);
                                if (result.supportVersion && result.supportVersion.length) {
                                    if (result.supportVersion.length === 1)
                                        data.push(`增量支持版本=${result.supportVersion.shift()}`);
                                    else
                                        data.push(`增量支持版本=${result.supportVersion.shift()} - ${result.supportVersion.pop()}`);
                                }
                            }
                            else {
                                data.push(`没有需要构建的更新`);
                            }
                        });
                    }
                    FileUtils_1.default.rm(buildResultCacheFile);
                }
                const customData = ProcessUtils_1.default.getArg('--data', value => value && !value.startsWith('--'));
                customData && data.unshift(...customData.split(';'));
                const handler = new (robotType === 'wechat' ? WechatHandler_1.default : FeishuHandler_1.default)(robotKey, key ? `SubGame - ${key}` : `SubGame In Project`, project, data.join(';'));
                command === 'begin' ? yield handler.begin() : yield handler.end();
            }
            break;
        case 'package':
            {
                const outputDir = path_1.default.join(project, 'build', 'subgame', platform);
                FileUtils_1.default.rm(outputDir);
                const buildPath = path_1.default.join(project, 'build', platform === 'android' ? 'jsb-default' : platform, 'assets');
                const packageAll = ProcessUtils_1.default.haveArg('--all');
                const keys = [];
                if (packageAll) {
                    const subGameDir = fs_1.default.readdirSync(buildPath);
                    subGameDir.forEach(dir => {
                        if (dir === 'main' || dir === 'internal' || dir === 'resources' || dir.startsWith('_'))
                            return;
                        const stat = fs_1.default.statSync(path_1.default.join(buildPath, dir));
                        if (stat.isFile())
                            return;
                        keys.push(dir);
                    });
                }
                else {
                    const key = ProcessUtils_1.default.getArg('--key', value => fs_1.default.existsSync(path_1.default.join(buildPath, value)));
                    if (!key) {
                        console.error(`illegal parameter --key or file not exists`);
                        break;
                    }
                    keys.push(key);
                }
                switch (platform) {
                    case 'android':
                        {
                            if (!mode) {
                                console.error(`illegal parameter --mode`);
                                break;
                            }
                            const xxtea = ProcessUtils_1.default.getArg('--xxtea', value => !!value && !value.startsWith('--')) || '';
                            const zipCompressJs = !!ProcessUtils_1.default.haveArg('--zipCompressJs');
                            const url = ProcessUtils_1.default.getArg('--url', value => !!value && value.startsWith('http'));
                            const codeVersion = ProcessUtils_1.default.getArg('--version', value => !!value);
                            const results = [];
                            for (const key of keys) {
                                const result = yield (0, PackagerAndroid_1.default)(project, key, codeVersion, mode, url, xxtea, zipCompressJs, isolate);
                                result && results.push(result);
                            }
                            const buildResult = { results };
                            const backup = ProcessUtils_1.default.haveArg('--backup');
                            if (backup) {
                                const dateDir = (new Date()).toLocaleString().replace(/[\/\\:]/gm, '-');
                                buildResult.backupTimestamp = dateDir;
                                const backupDir = path_1.default.join(project, '.subgame_bak', dateDir);
                                FileUtils_1.default.copy(outputDir, backupDir);
                                fs_1.default.writeFileSync(path_1.default.join(backupDir, 'build_result.json'), JSON.stringify(results));
                            }
                            FileUtils_1.default.mkdir(path_1.default.dirname(buildResultCacheFile));
                            fs_1.default.writeFileSync(buildResultCacheFile, JSON.stringify(buildResult));
                            console.warn(`save build result ${buildResultCacheFile}`);
                        }
                        break;
                    case 'web-mobile':
                        {
                            for (const key of keys) {
                                (0, PackagerWeb_1.default)(project, key, isolate);
                            }
                        }
                        break;
                }
            }
            break;
    }
}))();
