"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Utils = __importStar(require("../../util/src"));
const Store = __importStar(require("./store"));
const Path = __importStar(require("path"));
const FS = __importStar(require("fs"));
const pixelmatch_1 = __importDefault(require("pixelmatch"));
const Pngjs = __importStar(require("pngjs"));
function check(resultpath) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, function* () {
        const reports = new Array();
        const rcrPaths = new Array();
        Utils.FS.walk(resultpath, (root, name, stats) => {
            if (stats.isFile() && Path.extname(name) === '.rcr') {
                rcrPaths.push(Path.join(root, name));
            }
        });
        Utils.Console.info(`提取用例元数据 [${rcrPaths.length}] 个`);
        let index = 1;
        for (const rcrpath of rcrPaths) {
            const meta = JSON.parse(FS.readFileSync(rcrpath).toString());
            try {
                Utils.Console.info(`分析用例 [${meta.case.ID}] [${index}/${rcrPaths.length}]`);
                Utils.Console.info(`提取基线`);
                const baseline = yield Store.Store.baseline(meta.case.ID, meta.environment.ID);
                let report = {
                    caseID: meta.case.ID
                };
                if (baseline) {
                    Utils.Console.info(`比对特征`);
                    report = yield _check({
                        caseID: meta.case.ID,
                        envID: meta.environment.ID,
                        portraits: meta.portraits
                    }, baseline, Path.dirname(rcrpath));
                }
                else {
                    report = {
                        caseID: meta.case.ID,
                        casePath: rcrpath,
                        stacks: [{
                                success: false,
                                message: `未找到对应的基线特征`
                            }]
                    };
                }
                reports.push(report);
                Utils.Console.info(`校验结果 : ${report.stacks && (((_a = report.stacks) === null || _a === void 0 ? void 0 : _a.filter(v => v.success === false).length) > 0) ? '失败' : '成功'}`);
            }
            catch (error) {
                Utils.Console.info(`发生异常 : [${(_b = meta.case) === null || _b === void 0 ? void 0 : _b.ID}] ${error}`);
                reports.push({
                    caseID: `${meta.case.ID}`,
                    casePath: rcrpath,
                    stacks: [{
                            success: false,
                            message: `${error}`
                        }]
                });
            }
            index++;
        }
        Utils.Console.info(`总计分析 ${rcrPaths.length} 个`);
        return Promise.resolve(reports);
    });
}
exports.check = check;
function _check(meta, baseline, root) {
    var _a, _b, _c, _d, _e, _f, _g;
    return __awaiter(this, void 0, void 0, function* () {
        const report = {
            caseID: meta.caseID,
            stacks: new Array()
        };
        if (meta.portraits) {
            for (let index = 0; index < meta.portraits.length; index++) {
                try {
                    const metaPortrait = meta.portraits[index];
                    const baselinePortrait = baseline.portraits && baseline.portraits.length > index ? baseline.portraits[index] : undefined;
                    if (metaPortrait && baselinePortrait) {
                        if (metaPortrait.type === baselinePortrait.type) {
                            if (metaPortrait.type === Store.Store.PtType.Image) {
                                (_a = report.stacks) === null || _a === void 0 ? void 0 : _a.push(yield _check4image(metaPortrait, baselinePortrait, root));
                            }
                            else if (metaPortrait.type === Store.Store.PtType.Text) {
                                (_b = report.stacks) === null || _b === void 0 ? void 0 : _b.push(yield _check4text(metaPortrait, baselinePortrait, root));
                            }
                            else {
                                (_c = report.stacks) === null || _c === void 0 ? void 0 : _c.push({
                                    success: false,
                                    message: `不支持的特征类型 [meta:${metaPortrait.type}]`
                                });
                                break;
                            }
                        }
                        else {
                            (_d = report.stacks) === null || _d === void 0 ? void 0 : _d.push({
                                success: false,
                                message: `特征类型不匹配 [meta:${metaPortrait.type} baseline:${baselinePortrait.type}]`
                            });
                            break;
                        }
                    }
                    else {
                        (_e = report.stacks) === null || _e === void 0 ? void 0 : _e.push({
                            success: false,
                            message: `基线内未找到与之匹配的特征信息`
                        });
                        break;
                    }
                }
                catch (error) {
                    (_f = report.stacks) === null || _f === void 0 ? void 0 : _f.push({
                        success: false,
                        message: `发生异常 : ${error}`
                    });
                    continue;
                }
            }
        }
        else {
            (_g = report.stacks) === null || _g === void 0 ? void 0 : _g.push({
                success: false,
                message: `无特征信息`
            });
        }
        return Promise.resolve(report);
    });
}
function _check4image(meta, baseline, root) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, function* () {
        const metaImagePath = Path.join(root, `${(_a = meta.value) === null || _a === void 0 ? void 0 : _a.name}`);
        const baselineImagePath = Path.join(Store.Store.imageRootPath, `${(_b = baseline.value) === null || _b === void 0 ? void 0 : _b.name}`);
        const metaImg = Pngjs.PNG.sync.read(FS.readFileSync(metaImagePath));
        const baselineImg = Pngjs.PNG.sync.read(FS.readFileSync(baselineImagePath));
        const { width, height } = metaImg;
        const diffImg = new Pngjs.PNG({ width, height });
        const mismatched = pixelmatch_1.default(metaImg.data, baselineImg.data, diffImg.data, width, height, { threshold: 0.1 });
        if (mismatched > 1000) {
            return Promise.resolve({
                success: false,
                message: `不匹配的像素规模 : ${mismatched}`,
                images: {
                    meta: metaImg,
                    baseline: baselineImg,
                    diff: diffImg
                }
            });
        }
        else {
            return Promise.resolve({
                success: true
            });
        }
    });
}
function _check4text(meta, baseline, root) {
    return __awaiter(this, void 0, void 0, function* () {
        if (meta.value === baseline.value) {
            return Promise.resolve({
                success: true
            });
        }
        else {
            return Promise.resolve({
                success: false,
                message: `文本内容比对失败`
            });
        }
    });
}
//# sourceMappingURL=check.js.map