/*
 * Copyright 2017-2020 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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());
    });
};
import Debug from 'debug';
const debug = Debug('core/plugins/preloader');
debug('loading');
import { mainPath, webpackPath } from './path';
import { isHeadless } from '../core/capabilities';
import { ImplForPlugins } from '../core/command-tree';
import { registerSidecarBadge as registerBadge } from '../webapp/views/registrar/badges';
import { registerSidecarMode as registerMode } from '../webapp/views/registrar/modes';
import { registerSessionInitializer } from '../session/registrar';
class PreloaderRegistrarImpl extends ImplForPlugins {
    // why does eslint consider this to be a useless constructor??
    // eslint-disable-next-line no-useless-constructor
    constructor(plugin) {
        super(plugin);
    }
    registerMode(registration) {
        registerMode(registration);
    }
    registerModes(...registrations) {
        registrations.forEach(_ => this.registerMode(_));
    }
    registerBadge(registration) {
        registerBadge(registration);
    }
    registerBadges(...registrations) {
        registrations.forEach(_ => this.registerBadge(_));
    }
    /** session initializers */
    registerSessionInitializer(init) {
        registerSessionInitializer(init);
    }
}
/**
 * This module allows for plugins to register themselves to be
 * preloaded at startup, rather than in response to a user command
 *
 */
export default (prescan) => __awaiter(void 0, void 0, void 0, function* () {
    debug('init');
    const jobs = Promise.all(prescan.preloads.map((module) => __awaiter(void 0, void 0, void 0, function* () {
        // extends the capabilities of Kui
        try {
            debug('preloading capabilities.1 %s', module.path);
            const registrationRef = module.path.charAt(0) === '/'
                ? yield import(/* webpackIgnore: true */ module.path)
                : isHeadless()
                    ? yield import(/* webpackIgnore: true */ mainPath(module.path))
                    : module.route === 'client'
                        ? require(/* webpackMode: "lazy" */ '@kui-shell/client/' + 'mdist/preload')
                        : yield import(
                        /* webpackMode: "lazy" */ '@kui-shell/plugin-' + webpackPath(module.route) + '/mdist/preload');
            debug('preloading capabilities.2 %s', module.path);
            const registration = registrationRef.registerCapability;
            if (registration && typeof registration === 'function') {
                yield registration(new PreloaderRegistrarImpl(module.route));
                debug('registered capabilities %s', module.path);
            }
            else {
                debug('no registered capabilities %s', module.path);
            }
        }
        catch (err) {
            debug('error registering capabilities', module.path, err);
            console.error(err);
        }
    })))
        .then(() => __awaiter(void 0, void 0, void 0, function* () {
        yield import('../core/events').then(({ eventBus }) => {
            eventBus.once('/tab/new', (tab) => {
                if (tab._kui_session === undefined) {
                    tab._kui_session = Promise.resolve();
                }
            });
        });
    }))
        .then(() => Promise.all(prescan.preloads.map((module) => __awaiter(void 0, void 0, void 0, function* () {
        // FIXME to support field-installed plugin paths
        try {
            debug('preloading misc %s', module.path);
            // NOTE ON @kui-shell relativization: this is important so that
            // webpack can be isntructed to pull in the plugins into the
            // build see the corresponding NOTE in ./assembler.ts and
            // ./plugins.ts
            const registrationRef = module.path.charAt(0) === '/'
                ? yield import(/* webpackIgnore: true */ module.path)
                : isHeadless()
                    ? yield import(/* webpackIgnore: true */ mainPath(module.path))
                    : module.route === 'client'
                        ? require(/* webpackMode: "lazy" */ '@kui-shell/client/' + 'mdist/preload')
                        : yield import(
                        /* webpackMode: "lazy" */ '@kui-shell/plugin-' + webpackPath(module.route) + '/mdist/preload');
            const registration = registrationRef.default || registrationRef;
            if (registration && typeof registration === 'function') {
                yield registration(new PreloaderRegistrarImpl(module.route));
            }
            debug('done preloading %s', module.path);
        }
        catch (err) {
            debug('error invoking preload', module.path, err);
            console.error(err);
        }
    }))));
    try {
        yield jobs;
    }
    catch (err) {
        console.error(err);
    }
    debug('done');
});
//# sourceMappingURL=preloader.js.map