import { detach, isNullOrUndefined, updateCSSText } from '@syncfusion/ej2-base';
import { DropDownButton } from '@syncfusion/ej2-splitbuttons';
import { ColorPicker } from '@syncfusion/ej2-inputs';
import { ToolbarRenderer } from './common/index';
import { getInlineToolbarItems, transformIntoToolbarItem } from '../../common/utils/index';
import { events } from '../../common/constant';
import * as constants from '../../common/constant';
/**
 * InlineToolbarModule class is used to render the inline toolbar for the block editor.
 *
 * @hidden
 */
var InlineToolbarModule = /** @class */ (function () {
    function InlineToolbarModule(editor) {
        this.editor = editor;
        this.toolbarRenderer = new ToolbarRenderer(this.editor);
        this.addEventListeners();
        this.init();
        this.bindTooltip();
    }
    InlineToolbarModule.prototype.addEventListeners = function () {
        this.editor.blockManager.observer.on('enableDisableTbarItems', this.enableDisableTbarItems, this);
        this.editor.on(events.inlineToolbarCreated, this.handleInlineToolbarCreated, this);
        this.editor.on(events.inlineToolbarItemClick, this.handleInlineToolbarItemClick, this);
        this.editor.on(events.moduleChanged, this.onPropertyChanged, this);
        this.editor.on(events.rtlChanged, this.applyRtlSettings, this);
        this.editor.on(events.destroy, this.destroy, this);
    };
    InlineToolbarModule.prototype.removeEventListeners = function () {
        this.editor.blockManager.observer.off('enableDisableTbarItems', this.enableDisableTbarItems);
        this.editor.off(events.inlineToolbarCreated, this.handleInlineToolbarCreated);
        this.editor.off(events.inlineToolbarItemClick, this.handleInlineToolbarItemClick);
        this.editor.off(events.moduleChanged, this.onPropertyChanged);
        this.editor.off(events.rtlChanged, this.applyRtlSettings);
        this.editor.off(events.destroy, this.destroy);
    };
    InlineToolbarModule.prototype.init = function () {
        this.toolbarEle = this.editor.createElement('div', {
            id: (this.editor.element.id + constants.BLOCKEDITOR_INLINETBAR_ID),
            className: constants.BLOCKEDITOR_INLINETBAR_CLS
        });
        this.editor.element.appendChild(this.toolbarEle);
        this.toolbarObj = this.renderToolbar({
            element: this.toolbarEle,
            items: this.getToolbarItems(this.editor.inlineToolbarSettings.items),
            width: this.editor.inlineToolbarSettings.popupWidth,
            overflowMode: 'MultiRow'
        });
        var popupElement = this.editor.createElement('div', {
            id: (this.editor.element.id + constants.INLINE_TBAR_POPUP_ID),
            className: constants.INLINE_TBAR_POPUP_CLS
        });
        this.editor.element.appendChild(popupElement);
        this.editor.blockManager.observer.notify('toolbarCreated');
    };
    InlineToolbarModule.prototype.bindTooltip = function () {
        this.inlineToolbarTooltip = this.editor.tooltipRenderer.renderTooltip({
            cssClass: constants.INLINE_TBAR_TOOLTIP_CLS,
            position: 'TopCenter',
            target: '.' + constants.TBAR_ITEM_CLS,
            windowCollision: true,
            element: document.querySelector('#' + this.editor.element.id + constants.INLINE_TBAR_POPUP_ID)
        });
    };
    /**
     * Render the inline toolbar for the block editor.
     *
     * @param {IToolbarRenderOptions} args - The options for rendering the toolbar.
     * @returns {Toolbar} The rendered toolbar instance.
     * @hidden
     */
    InlineToolbarModule.prototype.renderToolbar = function (args) {
        return this.toolbarRenderer.renderToolbar(args);
    };
    InlineToolbarModule.prototype.handleInlineToolbarCreated = function () {
        if (this.hasToolbarItemId('color')) {
            this.initializeColorPickerAndDropdown('color');
        }
        if (this.hasToolbarItemId('bgColor')) {
            this.initializeColorPickerAndDropdown('bgColor');
        }
    };
    InlineToolbarModule.prototype.handleInlineToolbarItemClick = function (args) {
        var itemClickArgs = {
            item: getInlineToolbarItems().find(function (item) { return item.id === args.item.id; }),
            event: args.originalEvent,
            isInteracted: Object.keys(args.originalEvent).length > 0,
            cancel: false
        };
        if (this.editor.inlineToolbarSettings.itemClick) {
            this.editor.inlineToolbarSettings.itemClick.call(this.editor, itemClickArgs);
        }
        if (itemClickArgs.cancel) {
            args.cancel = true;
            return;
        }
        this.editor.blockManager.observer.notify('inlineToolbarItemClick', args);
    };
    InlineToolbarModule.prototype.enableDisableTbarItems = function (args) {
        this.toolbarObj.enableItems(args.items, args.isEnable);
    };
    InlineToolbarModule.prototype.initializeColorPickerAndDropdown = function (type) {
        var toolbarElement = document.querySelector('#' + this.editor.element.id + constants.BLOCKEDITOR_INLINETBAR_ID);
        if (!toolbarElement) {
            return;
        }
        var pickerElement = this.editor.createElement('input', { attrs: { type: 'color' } });
        var colorPicker = this.createColorPicker(type, pickerElement);
        var colorBtn = toolbarElement.querySelector("#toolbar-" + type.toLowerCase() + "-dropdown");
        if (colorBtn) {
            var dropDown = this.createDropDown({
                instance: { target: colorPicker.element.closest('.e-colorpicker-wrapper') },
                element: colorBtn,
                inlineClass: "e-inline-" + type + "-icon",
                type: type
            });
            if (type === 'color') {
                this.textPickerElement = pickerElement;
                this.textColorPicker = colorPicker;
                this.textColorDDB = dropDown;
            }
            else {
                this.bgPickerElement = pickerElement;
                this.bgColorPicker = colorPicker;
                this.bgColorDDB = dropDown;
            }
        }
    };
    InlineToolbarModule.prototype.createColorPicker = function (type, element) {
        var _this = this;
        element.id = type === 'color' ? 'be-colorPicker' : 'be-bgColorPicker';
        document.body.appendChild(element);
        var colorPicker = new ColorPicker({
            mode: 'Palette',
            inline: true,
            modeSwitcher: false,
            showButtons: false,
            noColor: true,
            value: '#000000',
            cssClass: 'e-be-color-picker',
            change: function (args) {
                _this.handleColorChange(type, args);
            }
        });
        colorPicker.appendTo(element);
        return colorPicker;
    };
    InlineToolbarModule.prototype.createDropDown = function (args) {
        var dropDown = new DropDownButton({
            target: args.instance.target,
            cssClass: args.instance.cssClass,
            createPopupOnClick: args.instance.createPopupOnClick
        });
        dropDown.appendTo(args.element);
        var iconWrapper = this.editor.createElement('span', { className: 'e-be-color-icon-wrapper' });
        var iconElement = this.editor.createElement('span', { className: args.inlineClass });
        var cssText = 'border-bottom: 3px solid #000000;';
        updateCSSText(iconElement, cssText);
        iconWrapper.appendChild(iconElement);
        dropDown.element.insertBefore(iconWrapper, dropDown.element.querySelector('.e-caret'));
        return dropDown;
    };
    InlineToolbarModule.prototype.handleColorChange = function (type, args) {
        this.editor.blockManager.observer.notify('handleColorpickerChange', { type: type, value: args.currentValue.rgba });
        var dropdownButton = type === 'color' ? this.textColorDDB : this.bgColorDDB;
        dropdownButton.toggle();
    };
    InlineToolbarModule.prototype.applyRtlSettings = function () {
        if (this.toolbarObj) {
            this.toolbarObj.enableRtl = this.editor.enableRtl;
        }
    };
    /**
     * For internal use only - Get the module name.
     *
     * @returns {void}
     * @hidden
     */
    InlineToolbarModule.prototype.getModuleName = function () {
        return 'inlineToolbarSettings';
    };
    /**
     * Destroys the inline toolbar module and cleans up resources
     *
     * @returns {void}
     */
    InlineToolbarModule.prototype.destroy = function () {
        this.removeEventListeners();
        if (this.toolbarObj) {
            this.toolbarObj.destroy();
            detach(this.toolbarEle);
            this.toolbarObj = null;
        }
        if (this.textColorDDB) {
            this.textColorDDB.destroy();
            this.textColorDDB = null;
        }
        if (this.bgColorDDB) {
            this.bgColorDDB.destroy();
            this.bgColorDDB = null;
        }
        if (this.textColorPicker) {
            this.textColorPicker.destroy();
            detach(this.textPickerElement);
            this.textColorPicker = null;
        }
        if (this.bgColorPicker) {
            this.bgColorPicker.destroy();
            detach(this.bgPickerElement);
            this.bgColorPicker = null;
        }
        if (this.inlineToolbarTooltip) {
            this.inlineToolbarTooltip.destroy();
        }
        this.toolbarRenderer = null;
        this.inlineToolbarTooltip = null;
    };
    /**
     * Handles property changes to update the toolbar configuration
     *
     * @param {BlockEditorModel} e - specifies the element.
     * @returns {void}
     * @hidden
     */
    InlineToolbarModule.prototype.onPropertyChanged = function (e) {
        if (e.module !== this.getModuleName()) {
            return;
        }
        var newProp = e.newProp.inlineToolbarSettings;
        var oldProp = e.oldProp.inlineToolbarSettings;
        if (!isNullOrUndefined(newProp)) {
            for (var _i = 0, _a = Object.keys(newProp); _i < _a.length; _i++) {
                var prop = _a[_i];
                switch (prop) {
                    case 'popupWidth':
                        this.editor.blockManager.observer.notify('popupWidthChanged', { value: newProp.popupWidth });
                        break;
                    case 'items': {
                        var flattenedToolbarItems = this.getToolbarItems(newProp.items);
                        this.toolbarObj.items = flattenedToolbarItems;
                        break;
                    }
                }
            }
        }
    };
    InlineToolbarModule.prototype.getToolbarItems = function (items) {
        var defaults = getInlineToolbarItems();
        var resolved = items.map(function (item) {
            if (typeof item === 'string') {
                var match = defaults.find(function (d) {
                    return d.command && d.command.toLowerCase() === item.toLowerCase();
                });
                return match ? match : item;
            }
            return item;
        });
        return transformIntoToolbarItem(resolved);
    };
    InlineToolbarModule.prototype.hasToolbarItemId = function (targetId) {
        var items = this.getToolbarItems(this.editor.inlineToolbarSettings.items);
        return items.some(function (item) {
            var id = item.id;
            return id && id.toLowerCase() === targetId.toLowerCase();
        });
    };
    return InlineToolbarModule;
}());
export { InlineToolbarModule };
