"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");
function buildCases(path) {
    return __awaiter(this, void 0, void 0, function* () {
        const cost = new Utils.Cost();
        const cases = new Array();
        const projects = pickProjects(path);
        Utils.Console.info(`扫描可识别的Cube工程（${projects.length}个）[${path}]`);
        let index = 1;
        let successed = 0;
        let failured = 0;
        for (const root of projects) {
            Utils.Console.info(`开始构造用例[${index}/${projects.length}]`);
            index++;
            try {
                const acase = yield buildCase(root);
                //  存储用例配置信息
                Utils.Console.info(`存储用例配置信息至[${Path.join(root, `${acase.id}.rcase`)}]`);
                FS.writeFileSync(Path.join(root, `${acase.id}.rcase`), JSON.stringify(acase, undefined, 2), { encoding: 'utf8' });
                cases.push(acase);
                successed++;
            }
            catch (error) {
                Utils.Console.error(`构造用例异常: ${error} [${root}]`);
                failured++;
                continue;
            }
        }
        Utils.Console.info(`共成功构造用例${successed}个，失败${failured}个 [${path}]`);
        cost.mark();
        return Promise.resolve(cases);
    });
}
exports.buildCases = buildCases;
function buildCase(path) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = JSON.parse(FS.readFileSync(Path.join(path, 'package.json')).toString());
        const folderName = Utils.FS.lastName(path);
        let acase = new Object(undefined);
        //  优先使用package.json内配置的字段
        if (pkg.case) {
            acase = Object.assign({}, pkg.case);
        }
        //  追加默认处理
        if (!acase.id) {
            acase.id = pkg.name;
            //  针对wpt工具导出的功能id相同的场景进行特殊处理
            if (acase.id === 'CubeApp') {
                acase.id = folderName;
            }
        }
        if (!acase.poles) {
            acase.poles = 'paint_message';
        }
        if (!acase.type) {
            //  暂未支持appx
            if (pkg.type === 'templates') {
                acase.type = 'falcon';
            }
            else if (pkg.type === 'appx') {
                acase.type = 'appx';
            }
            else {
                acase.type = 'vue';
            }
        }
        if (!acase.subtype) {
            acase.subtype = 'only_paint_check';
        }
        //  装载信息填充
        let launchType = 'unknown';
        if (pkg.type === 'templates') {
            launchType = 'falcon';
        }
        else if (pkg.type === 'application') {
            launchType = 'vue';
        }
        acase.iOSScheme = `rubik:/launch?type=${launchType}&path=CubeDebug.bundle%2frubik%2fproject%2f${acase.type}%2f${folderName}`;
        acase.projectPath = `${acase.type}/${folderName}`;
        acase.root = path;
        acase.sql = `INSERT OR REPLACE INTO rkt_case_manifest (ID,type,subtype,iosScheme,poles) VALUES ('${acase.id}','${acase.type}','${acase.subtype}','${acase.iOSScheme}','${acase.poles}')`;
        Utils.Console.info(`创建用例配置:\n${JSON.stringify(acase, undefined, 2)}`);
        return Promise.resolve(acase);
    });
}
function pickProjects(root) {
    const roots = new Array();
    Utils.FS.walk(root, (path, name, stats) => {
        if (name === 'package.json') {
            roots.push(path);
        }
    });
    return roots;
}
function buildTinyCases(path) {
    if (!FS.existsSync(Path.join(path, 'dist/native'))) {
        return Promise.reject(Error(`未找到可提取的cube编译产物`));
    }
    Utils.Console.info(`提取工程配置 [${Path.join(path, 'dist/package/package.json')}]`);
    const pkg = JSON.parse(FS.readFileSync(Path.join(path, 'dist/package/package.json')).toString());
    Utils.Console.info(`提取应用配置 [${Path.join(path, 'dist/native/appConfig.json')}]`);
    const app = JSON.parse(FS.readFileSync(Path.join(path, 'dist/native/appConfig.json')).toString());
    let index = 1;
    for (const page of app.pages) {
        Utils.Console.info(`构建页面用例 [${page}] [${index}/${app.pages.length}]`);
        let acase = new Object(undefined);
        //  优先使用package.json内配置的字段
        if (pkg.case) {
            acase = Object.assign({}, pkg.case);
        }
        //  追加默认处理
        if (!acase.poles) {
            acase.poles = 'paint_message';
        }
        if (!acase.id) {
            acase.id = `tiny_${acase.poles}_${pkg.name}_${page.split('/').join('-')}`;
        }
        if (!acase.type) {
            acase.type = "appx";
        }
        if (!acase.subtype) {
            acase.subtype = 'only_paint_check';
        }
        acase.iOSScheme = `rubik:/launch?type=${acase.type}&path=CubeDebug.bundle%2frubik%2fproject%2f${acase.type}%2f${pkg.name}%2findex.bundle.js&page=${page.split('/').join('%2f')}`;
        acase.projectPath = `${acase.type}/${pkg.name}/index.bundle.js`;
        acase.root = path;
        acase.sql = `INSERT OR REPLACE INTO rkt_case_manifest (ID,type,subtype,iosScheme,poles) VALUES ('${acase.id}','${acase.type}','${acase.subtype}','${acase.iOSScheme}','${acase.poles}')`;
        Utils.Console.info(`创建用例配置:\n${JSON.stringify(acase, undefined, 2)}`);
        //  存储用例配置信息
        Utils.Console.info(`存储用例配置信息至[${Path.join(path, `${acase.id}.rcase`)}]`);
        FS.writeFileSync(Path.join(path, `${acase.id}.rcase`), JSON.stringify(acase, undefined, 2), { encoding: 'utf8' });
        index++;
    }
    return Promise.resolve();
}
exports.buildTinyCases = buildTinyCases;
function clean(path, tiny = false) {
    Utils.Console.info(`清理工程内用例信息`);
    if (tiny) {
        const subpaths = FS.readdirSync(path);
        for (const name of subpaths) {
            if (FS.statSync(Path.join(path, name)).isFile() && Path.extname(name) === '.rcase') {
                Utils.Console.info(`删除用例配置信息 [${Path.join(path, name)}]`);
                FS.unlinkSync(Path.join(path, name));
            }
        }
    }
    else {
        Utils.FS.walk(path, (root, name, stats) => {
            if (stats.isFile() && Path.extname(name) === '.rcase') {
                Utils.Console.info(`删除用例配置信息 [${Path.join(root, name)}]`);
                FS.unlinkSync(Path.join(root, name));
            }
        });
    }
    Utils.Console.info(`工程清理完成`);
    return Promise.resolve();
}
exports.clean = clean;
//# sourceMappingURL=build.js.map