"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const Utils = require("../../util/src");
const Path = require("path");
const FS = require("fs");
const DB = require("./db");
function install(casepath, cubepath, tiny = false) {
    return __awaiter(this, void 0, void 0, function* () {
        const cost = new Utils.Cost();
        Utils.Console.info(`开始装载用例集\n    用例集路径 [${casepath}]\n    Cube路径 [${cubepath}]`);
        yield iOS.install(casepath, cubepath, tiny);
        Utils.Console.info(`用例集装载完成`);
        cost.mark();
        return Promise.resolve();
    });
}
exports.install = install;
function update4baseline(baselinePath, cubepath) {
    return __awaiter(this, void 0, void 0, function* () {
        const cost = new Utils.Cost();
        Utils.Console.info(`开始更新基线信息\n    基线路径 [${baselinePath}]\n    Cube路径 [${cubepath}]`);
        yield iOS.update4baseline(baselinePath, cubepath);
        cost.mark();
        return Promise.resolve();
    });
}
exports.update4baseline = update4baseline;
var iOS;
(function (iOS) {
    function install(casepath, cubepath, tiny = false) {
        return __awaiter(this, void 0, void 0, function* () {
            Utils.Console.info(`装载到iOS环境...`);
            const isApp = () => {
                return Path.extname(cubepath) === '.app' ? true : false;
            };
            const dbpath = isApp() ? `CubeDebug.bundle/rubik/rubik.db` : `iOS/mQuick/CubeDebug/Resource/CubeDebug.bundle/rubik/rubik.db`;
            const respath = isApp() ? `CubeDebug.bundle/rubik/project` : `iOS/mQuick/CubeDebug/Resource/CubeDebug.bundle/rubik/project`;
            return yield _install(casepath, cubepath, dbpath, respath, tiny);
        });
    }
    iOS.install = install;
    function _install(casepath, cubepath, dbpath, respath, tiny = false) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const pickedCases = pickCases(casepath, tiny);
            Utils.Console.info(`提取用例配置信息(${pickedCases.length}个)`);
            const _dbpath = Path.join(cubepath, dbpath);
            Utils.Console.info(`打开用例数据库 [${_dbpath}]`);
            const db = new DB.DB();
            yield db.open(_dbpath);
            let index = 1;
            let successed = 0;
            let failured = 0;
            for (const apicked of pickedCases) {
                try {
                    Utils.Console.info(`安装用例[${index}/${pickedCases.length}]...`);
                    if (apicked.rcase.sql) {
                        Utils.Console.info(`更新用例manifest ${apicked.rcase.sql}`);
                        yield db.update((_a = apicked.rcase) === null || _a === void 0 ? void 0 : _a.sql);
                        const pjpath = Path.join(cubepath, respath, apicked.rcase.projectPath ? apicked.rcase.projectPath : "");
                        Utils.Console.info(`拷贝用例page工程 ${apicked.rdemoPath} => ${pjpath}`);
                        if (FS.existsSync(pjpath)) {
                            Utils.Console.info(`    用例page工程已存在，执行清理`);
                            Utils.FS.rmdirs(pjpath);
                        }
                        Utils.Console.info(`    用例page工程执行拷贝`);
                        Utils.FS.copy(apicked.rdemoPath, pjpath);
                    }
                    successed++;
                }
                catch (error) {
                    failured++;
                }
                index++;
            }
            yield db.close();
            Utils.Console.info(`共成功导入用例${successed}个，失败${failured}个`);
            return Promise.resolve();
        });
    }
    function update4baseline(baselinePath, cubepath) {
        return __awaiter(this, void 0, void 0, function* () {
            const isApp = Path.extname(cubepath) === '.app' ? true : false;
            const dbpath = isApp ? `CubeDebug.bundle/rubik/rubik.db` : `iOS/mQuick/CubeDebug/Resource/CubeDebug.bundle/rubik/rubik.db`;
            Utils.Console.info(`打开数据库 ${dbpath}`);
            const db = new DB.DB();
            yield db.open(Path.join(cubepath, dbpath));
            const sqls = new Array();
            Utils.FS.walk(baselinePath, (root, name, stats) => {
                if (stats.isFile() && Path.extname(name) === '.json') {
                    const info = JSON.parse(FS.readFileSync(Path.join(root, name)).toString());
                    if (info.sql && info.values) {
                        sqls.push(info);
                    }
                }
            });
            Utils.Console.info(`共扫描基线配置文件 ${sqls.length} 个`);
            let success = 0;
            let failure = 0;
            let index = 1;
            for (const asql of sqls) {
                try {
                    yield db.update(asql.sql, asql.values);
                    success++;
                    Utils.Console.info(`执行基线更新成功 [${index}/${sqls.length}]`);
                }
                catch (error) {
                    failure++;
                    Utils.Console.error(`执行基线更新失败 [${index}/${sqls.length}] : ${error}`);
                }
                index++;
            }
            Utils.Console.info(`共更新基线信息 ${sqls.length} 个，成功 ${success} ，失败 ${failure}`);
            yield db.close();
            return Promise.resolve();
        });
    }
    iOS.update4baseline = update4baseline;
})(iOS || (iOS = {}));
function pickCases(path, tiny = false) {
    const result = new Array();
    if (tiny) {
        //  小程序工程仅遍历根目录下文件，避免遍历node_modules文件夹
        const subpaths = FS.readdirSync(path);
        for (const name of subpaths) {
            if (FS.statSync(Path.join(path, name)).isFile() && Path.extname(name) === '.rcase') {
                result.push({
                    rcasePath: Path.join(path, name),
                    rdemoPath: Path.join(path, 'dist/native/index.bundle.js'),
                    rcase: JSON.parse(FS.readFileSync(Path.join(path, name)).toString())
                });
            }
        }
    }
    else {
        Utils.FS.walk(path, (root, name, stats) => {
            if (stats.isFile() && Path.extname(name) === '.rcase') {
                result.push({
                    rcasePath: Path.join(root, name),
                    rdemoPath: root,
                    rcase: JSON.parse(FS.readFileSync(Path.join(root, name)).toString())
                });
            }
        });
    }
    return result;
}
//# sourceMappingURL=install.js.map