"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 __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const Path = __importStar(require("path"));
const FS = __importStar(require("fs"));
const DB = __importStar(require("./db"));
const Utils = __importStar(require("../../util/src"));
var Store;
(function (Store) {
    const configPath = Path.join(process.env.HOME ? process.env.HOME : '', '.antcube/rubik.json');
    const config = FS.existsSync(configPath) ? JSON.parse(FS.readFileSync(configPath).toString()) : {};
    const rootPath = `${config['CaseStoreRoot']}`;
    const dbPath = Path.join(rootPath, 'case/store.db');
    Store.imageRootPath = Path.join(rootPath, 'case/image');
    function baseline(caseID, envID) {
        return __awaiter(this, void 0, void 0, function* () {
            const db = new DB.DB();
            yield db.open(dbPath);
            const rows = yield db.select(`select * from rkt_case_baseline_portrait where caseID = ?`, [`${caseID}`]);
            if (rows.length > 0) {
                const baseline = [...rows].pop();
                return Promise.resolve({
                    caseID,
                    envID: envID ? envID : '',
                    portraits: JSON.parse(`${baseline.content ? baseline.content : '[]'}`)
                });
            }
            yield db.close();
            return Promise.resolve(undefined);
        });
    }
    Store.baseline = baseline;
    function updateBaseline(path) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const cost = new Utils.Cost();
            const rcrPaths = new Array();
            Utils.FS.walk(path, (root, name, stats) => {
                if (stats.isFile() && Path.extname(name) === '.rcr') {
                    rcrPaths.push(Path.join(root, name));
                }
            });
            Utils.Console.info(`提取基线元数据 [${rcrPaths.length}] 个`);
            const db = new DB.DB();
            yield db.open(dbPath);
            Utils.Console.info(`打开仓库DB [${dbPath}]`);
            let index = 1;
            let failure = 0;
            for (const rcrpath of rcrPaths) {
                const rcr = JSON.parse(FS.readFileSync(rcrpath).toString());
                try {
                    //  存储配置信息
                    Utils.Console.info(`更新基线 [特征] 信息 [${rcr.case.ID}] [${index}/${rcrPaths.length}]`);
                    yield db.update(`insert or replace into rkt_case_baseline_portrait (caseID, envID, content) values(?,?,?)`, [
                        `${rcr.case.ID}`,
                        `${rcr.environment.ID}`,
                        `${JSON.stringify(rcr.portraits)}`
                    ]);
                    Utils.Console.info(`更新基线 [环境] 信息 [${rcr.environment.ID}]`);
                    yield db.update(`insert or replace into rkt_case_baseline_environment (ID,deviceMode,deviceFirm,deviceIMEI,osPlatform,osVersion,engineVersion) values (?,?,?,?,?,?,?)`, [
                        `${rcr.environment.ID}`,
                        `${rcr.environment.deviceMode}`,
                        `${rcr.environment.deviceFirm}`,
                        `${rcr.environment.deviceIMEI}`,
                        `${rcr.environment.osPlatform}`,
                        `${rcr.environment.osVersion}`,
                        `${rcr.environment.engineVersion}`
                    ]);
                    //  存储资源数据
                    if (rcr.portraits) {
                        for (const portrait of rcr.portraits) {
                            if (portrait.type === PtType.Image) {
                                Utils.Console.info(`更新基线 [截图] 文件 [${portrait.value.name}]`);
                                Utils.FS.copy(Path.join(Path.dirname(rcrpath), `${portrait.value.name}`), Path.join(Store.imageRootPath, `${portrait.value.name}`));
                            }
                        }
                    }
                }
                catch (error) {
                    Utils.Console.error(`发生异常 : [${(_a = rcr.case) === null || _a === void 0 ? void 0 : _a.ID}] ${error}`);
                    failure++;
                }
                index++;
            }
            yield db.close();
            Utils.Console.info(`总计更新 [${rcrPaths.length}] 个，失败 ${failure} 个`);
            cost.mark();
            return Promise.resolve();
        });
    }
    Store.updateBaseline = updateBaseline;
    let PtType;
    (function (PtType) {
        PtType["Text"] = "text";
        PtType["Image"] = "image";
    })(PtType = Store.PtType || (Store.PtType = {}));
})(Store = exports.Store || (exports.Store = {}));
var ProjectType;
(function (ProjectType) {
    ProjectType["None"] = "none";
    ProjectType["Tiny"] = "tiny";
    ProjectType["Vue"] = "vue";
    ProjectType["Falcon"] = "falcon";
})(ProjectType = exports.ProjectType || (exports.ProjectType = {}));
function projectType(root) {
    if (FS.existsSync(Path.join(root, 'package.json'))) {
        if (FS.existsSync(Path.join(root, 'src/app.js')) && FS.existsSync(Path.join(root, 'src/app.json'))) {
            return ProjectType.Tiny;
        }
        const pkg = JSON.parse(FS.readFileSync(Path.join(root, `package.json`)).toString());
        if (pkg.type === 'application') {
            return ProjectType.Vue;
        }
        else if (pkg.type === 'templates') {
            return ProjectType.Falcon;
        }
    }
    return ProjectType.None;
}
exports.projectType = projectType;
function pickProjects(root) {
    const roots = new Array();
    if (!FS.statSync(root).isDirectory()) {
        //  滤除非文件夹类型
        return roots;
    }
    const ptype = projectType(root);
    if (ProjectType.None !== ptype) {
        roots.push(root);
    }
    else {
        //  包含子工程
        const subpaths = FS.readdirSync(root);
        for (const subpath of subpaths) {
            roots.push(...pickProjects(Path.join(root, subpath)));
        }
    }
    return roots;
}
exports.pickProjects = pickProjects;
//# sourceMappingURL=store.js.map