"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GuiReportBuilder = void 0;
const lodash_1 = __importDefault(require("lodash"));
const static_1 = require("./static");
const gui_1 = require("../tests-tree-builder/gui");
const constants_1 = require("../constants");
const server_utils_1 = require("../server-utils");
const common_utils_1 = require("../common-utils");
const utils_1 = require("../test-adapter/utils");
class GuiReportBuilder extends static_1.StaticReportBuilder {
    constructor(htmlReporter, pluginConfig, options) {
        super(htmlReporter, pluginConfig, options);
        this._testsTree = gui_1.GuiTestsTreeBuilder.create({ toolName: constants_1.ToolName.Testplane, baseHost: pluginConfig.baseHost });
        this._skips = [];
    }
    setApiValues(values) {
        this._apiValues = values;
        return this;
    }
    reuseTestsTree(tree) {
        this._testsTree.reuseTestsTree(tree);
        // Fill test attempt manager with data from db
        for (const [, testResult] of Object.entries(tree.results.byId)) {
            this._testAttemptManager.registerAttempt({
                fullName: testResult.suitePath.join(constants_1.TESTPLANE_TITLE_DELIMITER),
                browserId: testResult.name
            }, testResult.status, testResult.attempt);
        }
    }
    getResult() {
        const { customGui } = this._pluginConfig;
        const config = { ...(0, server_utils_1.getConfigForStaticFile)(this._pluginConfig), customGui };
        this._testsTree.sortTree();
        return {
            tree: this._testsTree.tree,
            skips: this._skips,
            config,
            date: new Date().toString(),
            apiValues: this._apiValues
        };
    }
    getTestBranch(id) {
        return this._testsTree.getTestBranch(id);
    }
    getTestsDataToUpdateRefs(imageIds) {
        return this._testsTree.getTestsDataToUpdateRefs(imageIds);
    }
    getImageDataToFindEqualDiffs(imageIds) {
        return this._testsTree.getImageDataToFindEqualDiffs(imageIds);
    }
    undoAcceptImage(testResultWithoutAttempt, stateName) {
        const attempt = this._testAttemptManager.getCurrentAttempt(testResultWithoutAttempt);
        const testResult = (0, utils_1.copyAndUpdate)(testResultWithoutAttempt, { attempt });
        const resultId = testResult.id;
        const suitePath = testResult.testPath;
        const browserName = testResult.browserId;
        const resultData = this._testsTree.getResultDataToUnacceptImage(resultId, stateName);
        if (!resultData || !(0, common_utils_1.isUpdatedStatus)(resultData.status)) {
            return null;
        }
        const { imageId, status, timestamp, previousImage, shouldRemoveResult } = resultData;
        const previousExpectedPath = lodash_1.default.get(previousImage, 'expectedImg.path', null);
        const previousImageRefImgSize = lodash_1.default.get(previousImage, 'refImg.size', null);
        const shouldRemoveReference = lodash_1.default.isNull(previousImageRefImgSize);
        const shouldRevertReference = !shouldRemoveReference;
        let updatedImage, removedResult;
        if (shouldRemoveResult) {
            this._testsTree.removeTestResult(resultId);
            this._testAttemptManager.removeAttempt(testResult);
            removedResult = testResult;
        }
        else {
            updatedImage = this._testsTree.updateImageInfo(imageId, previousImage);
        }
        const newResult = (0, utils_1.copyAndUpdate)(testResult, { attempt: this._testAttemptManager.getCurrentAttempt(testResult) });
        this._deleteTestResultFromDb({ where: [
                `${constants_1.DB_COLUMNS.SUITE_PATH} = ?`,
                `${constants_1.DB_COLUMNS.NAME} = ?`,
                `${constants_1.DB_COLUMNS.STATUS} = ?`,
                `${constants_1.DB_COLUMNS.TIMESTAMP} = ?`,
                `json_extract(${constants_1.DB_COLUMNS.IMAGES_INFO}, '$[0].stateName') = ?`
            ].join(' AND ') }, JSON.stringify(suitePath), browserName, status, timestamp.toString(), stateName);
        return { updatedImage, removedResult, previousExpectedPath, shouldRemoveReference, shouldRevertReference, newResult };
    }
    getUpdatedReferenceTestStatus(testResult) {
        const getStateName = (imageInfo) => imageInfo.stateName;
        const resultId = testResult.id;
        const originalResult = this._testsTree.getTestBranch(resultId);
        const omittedImageStates = testResult.imagesInfo.map(getStateName);
        const estimatedStatus = (0, common_utils_1.determineStatus)({
            status: originalResult.result.status,
            error: originalResult.result.error,
            imagesInfo: originalResult.images.filter(image => !omittedImageStates.includes(getStateName(image)))
        });
        return estimatedStatus === constants_1.SUCCESS ? constants_1.UPDATED : estimatedStatus;
    }
    async addTestResult(formattedResultOriginal, updates) {
        const formattedResult = await super.addTestResult(formattedResultOriginal);
        if (formattedResult.status === constants_1.SKIPPED) {
            const { fullName: suite, skipReason: comment, browserId: browser } = formattedResult;
            this._skips.push({ suite, browser, comment });
        }
        const formattedResultWithImages = this._loadImagesFromPreviousAttempt(formattedResult);
        const resultOverrided = updates
            ? (0, utils_1.copyAndUpdate)(formattedResultWithImages, updates)
            : formattedResultWithImages;
        this._testsTree.addTestResult(resultOverrided);
        return resultOverrided;
    }
    _loadImagesFromPreviousAttempt(formattedResult) {
        if (formattedResult.status !== constants_1.UPDATED) {
            return formattedResult;
        }
        const previousResultId = (0, utils_1.copyAndUpdate)(formattedResult, { attempt: formattedResult.attempt - 1 }).id;
        const newImagesInfo = lodash_1.default.clone(this._testsTree.getImagesInfo(previousResultId));
        if (newImagesInfo.length) {
            formattedResult.imagesInfo?.forEach((imageInfo) => {
                const { stateName } = imageInfo;
                let index = lodash_1.default.findIndex(newImagesInfo, { stateName });
                index = index >= 0 ? index : lodash_1.default.findLastIndex(newImagesInfo);
                newImagesInfo[index] = imageInfo;
            });
        }
        return (0, utils_1.copyAndUpdate)(formattedResult, { imagesInfo: newImagesInfo });
    }
}
exports.GuiReportBuilder = GuiReportBuilder;
//# sourceMappingURL=gui.js.map