import $ from 'jquery';

import Differ from './differ';
import Toolbar from './image-differ-toolbar';

/**
 * @param {jQuery|HtmlElement} container - The container to use for this Image Differ
 * @returns {{on: Function, readyPromise: Promise}}
 */
function init(container) {
    const $container = $(container);
    let toolbar = new Toolbar($(bitbucket.internal.component.imageDiffer.toolbar.main()).prependTo($container));
    let differ = new Differ($container);

    toolbar.on('modeChanged', mode => differ.setMode(mode.newMode));

    const readyPromise = new $.Deferred();
    differ.init().done(enabledModes => {
        if (toolbar) {
            toolbar.init(enabledModes);
        }
        readyPromise.resolve({

            /**
             * Stop exposing this method when Stash no longer needs to retrigger Image Differ events
             * @deprecated
             */
            on: differ.on.bind(differ),
            enabledModes,
            _differ: differ,
            _toolbar: toolbar,
            destroy: () => {
                differ.destroy();
                differ = null;
                toolbar.destroy();
                toolbar = null;
            },
        });
    });
    return readyPromise;
}

export {
    init,
    Differ,
    Toolbar,
};
