"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeAbort = void 0;
const driver_1 = require("@applitools/driver");
const uniquify_environments_1 = require("./utils/uniquify-environments");
function makeAbort({ eyes, target, controller, environments: defaultEnvironments, spec, logger: mainLogger, }) {
    return async function abort({ settings, logger = mainLogger, } = {}) {
        var _a;
        logger = logger.extend(mainLogger);
        logger.log('Command "abort" is called with settings', settings);
        if (!eyes.running) {
            logger.log('Command "abort" will be ignored because eyes were already stopped');
            return;
        }
        else {
            ;
            eyes.running = false;
        }
        controller.abort();
        settings !== null && settings !== void 0 ? settings : (settings = {});
        if (!settings.testMetadata && (0, driver_1.isDriver)(target, spec)) {
            try {
                const driver = await (0, driver_1.makeDriver)({ spec, driver: target, relaxed: true, logger });
                settings.testMetadata = await driver.getSessionMetadata();
            }
            catch (error) {
                logger.warn('Command "abort" received an error during extracting driver metadata', error);
            }
        }
        (_a = settings.environments) !== null && _a !== void 0 ? _a : (settings.environments = defaultEnvironments);
        if (eyes.storage.size === 0 && settings.environments && settings.environments.length > 0) {
            const uniqueEnvironments = (0, uniquify_environments_1.uniquifyEnvironments)(settings.environments);
            logger.log('Command "abort" starting filler tests for environments', uniqueEnvironments);
            await Promise.all(uniqueEnvironments.map(environment => eyes.getBaseEyes({ settings: { environment }, logger })));
        }
        eyes.storage.forEach(async (item) => {
            var _a, _b;
            try {
                const eyes = await item.eyes;
                await eyes.abort({ settings, logger });
            }
            catch (error) {
                logger.warn('Command "abort" received an error during waiting for eyes instances in background', error);
                await ((_b = (_a = error === null || error === void 0 ? void 0 : error.info) === null || _a === void 0 ? void 0 : _a.eyes) === null || _b === void 0 ? void 0 : _b.abort({ settings, logger }));
            }
        });
    };
}
exports.makeAbort = makeAbort;
