"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeClose = void 0;
const driver_1 = require("@applitools/driver");
const uniquify_environments_1 = require("./utils/uniquify-environments");
function makeClose({ eyes, target, environments: defaultEnvironments, spec, logger: mainLogger, }) {
    return async function close({ settings, logger = mainLogger, } = {}) {
        var _a;
        logger = logger.extend(mainLogger);
        logger.log('Command "close" is called with settings', settings);
        if (!eyes.running) {
            logger.log('Command "close" will be ignored because eyes were already stopped');
            return;
        }
        else {
            ;
            eyes.running = false;
        }
        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 "close" 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 "close" starting filler tests for environments', settings.environments);
            await Promise.all(uniqueEnvironments.map(environment => eyes.getBaseEyes({ settings: { environment }, logger })));
        }
        eyes.storage.forEach(async (item) => {
            var _a, _b;
            try {
                const [eyes] = await Promise.all([item.eyes, ...item.jobs]);
                try {
                    await eyes.close({ settings, logger });
                }
                catch (error) {
                    logger.warn('Command "close" received an error during performing, trying to perform abort instead', error);
                    await eyes.abort({ settings, logger });
                }
            }
            catch (error) {
                logger.warn('Command "close" received an error during waiting for eyes instances in background', error);
                await ((_b = (_a = error.info) === null || _a === void 0 ? void 0 : _a.eyes) === null || _b === void 0 ? void 0 : _b.abort({ settings, logger }));
            }
        });
    };
}
exports.makeClose = makeClose;
