// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { WidgetTracker } from '@jupyterlab/apputils';
import { MimeDocumentFactory } from '@jupyterlab/docregistry';
import { IRenderMimeRegistry } from '@jupyterlab/rendermime';
import { ITranslator } from '@jupyterlab/translation';
import { LabIcon } from '@jupyterlab/ui-components';
import { Token } from '@lumino/coreutils';
import { AttachedProperty } from '@lumino/properties';
import { ILayoutRestorer } from './layoutrestorer';
/**
 * The mime document tracker token.
 */
export const IMimeDocumentTracker = new Token('@jupyterlab/application:IMimeDocumentTracker');
/**
 * Create rendermime plugins for rendermime extension modules.
 */
export function createRendermimePlugins(extensions) {
    const plugins = [];
    const namespace = 'application-mimedocuments';
    const tracker = new WidgetTracker({ namespace });
    extensions.forEach(mod => {
        let data = mod.default;
        // Handle CommonJS exports.
        if (!mod.hasOwnProperty('__esModule')) {
            data = mod;
        }
        if (!Array.isArray(data)) {
            data = [data];
        }
        data.forEach(item => {
            plugins.push(createRendermimePlugin(tracker, item));
        });
    });
    // Also add a meta-plugin handling state restoration
    // and exposing the mime document widget tracker.
    plugins.push({
        id: '@jupyterlab/application:mimedocument',
        optional: [ILayoutRestorer],
        provides: IMimeDocumentTracker,
        autoStart: true,
        activate: (app, restorer) => {
            if (restorer) {
                void restorer.restore(tracker, {
                    command: 'docmanager:open',
                    args: widget => ({
                        path: widget.context.path,
                        factory: Private.factoryNameProperty.get(widget)
                    }),
                    name: widget => `${widget.context.path}:${Private.factoryNameProperty.get(widget)}`
                });
            }
            return tracker;
        }
    });
    return plugins;
}
/**
 * Create rendermime plugins for rendermime extension modules.
 */
export function createRendermimePlugin(tracker, item) {
    return {
        id: item.id,
        requires: [IRenderMimeRegistry, ITranslator],
        autoStart: true,
        activate: (app, rendermime, translator) => {
            // Add the mime renderer.
            if (item.rank !== undefined) {
                rendermime.addFactory(item.rendererFactory, item.rank);
            }
            else {
                rendermime.addFactory(item.rendererFactory);
            }
            // Handle the widget factory.
            if (!item.documentWidgetFactoryOptions) {
                return;
            }
            const registry = app.docRegistry;
            let options = [];
            if (Array.isArray(item.documentWidgetFactoryOptions)) {
                options = item.documentWidgetFactoryOptions;
            }
            else {
                options = [
                    item.documentWidgetFactoryOptions
                ];
            }
            if (item.fileTypes) {
                item.fileTypes.forEach(ft => {
                    if (ft.icon) {
                        // upconvert the contents of the icon field to a proper LabIcon
                        ft = Object.assign(Object.assign({}, ft), { icon: LabIcon.resolve({ icon: ft.icon }) });
                    }
                    app.docRegistry.addFileType(ft);
                });
            }
            options.forEach(option => {
                const toolbarFactory = option.toolbarFactory
                    ? (w) => option.toolbarFactory(w.content.renderer)
                    : undefined;
                const factory = new MimeDocumentFactory({
                    renderTimeout: item.renderTimeout,
                    dataType: item.dataType,
                    rendermime,
                    modelName: option.modelName,
                    name: option.name,
                    primaryFileType: registry.getFileType(option.primaryFileType),
                    fileTypes: option.fileTypes,
                    defaultFor: option.defaultFor,
                    defaultRendered: option.defaultRendered,
                    toolbarFactory,
                    translator,
                    factory: item.rendererFactory
                });
                registry.addWidgetFactory(factory);
                factory.widgetCreated.connect((sender, widget) => {
                    Private.factoryNameProperty.set(widget, factory.name);
                    // Notify the widget tracker if restore data needs to update.
                    widget.context.pathChanged.connect(() => {
                        void tracker.save(widget);
                    });
                    void tracker.add(widget);
                });
            });
        }
    };
}
/**
 * Private namespace for the module.
 */
var Private;
(function (Private) {
    /**
     * An attached property for keeping the factory name
     * that was used to create a mimedocument.
     */
    Private.factoryNameProperty = new AttachedProperty({
        name: 'factoryName',
        create: () => undefined
    });
})(Private || (Private = {}));
//# sourceMappingURL=mimerenderers.js.map