import * as i0 from '@angular/core';
import { SecurityContext, Component, Inject, Optional, NgModule } from '@angular/core';
import * as i2 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i1 from '@wm/components/base';
import { PROP_STRING, PROP_ANY, PROP_BOOLEAN, PROP_NUMBER, register, registerFormWidget, APPLY_STYLES_TYPE, styler, provideAs, provideAsWidgetRef, WmComponentsModule } from '@wm/components/base';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { FormWidgetType, setCSS, setAttr, setHtml } from '@wm/core';
import { BaseFormCustomComponent } from '@wm/components/input';
import { extend } from 'lodash-es';

const richTextProps = new Map([
    ['class', PROP_STRING],
    ['datavaluesource', PROP_ANY],
    ['datavalue', PROP_STRING],
    ['height', PROP_STRING],
    ['hint', PROP_STRING],
    ['arialabel', PROP_STRING],
    ['name', PROP_STRING],
    ['placeholder', PROP_STRING],
    ['readonly', PROP_BOOLEAN],
    ['show', { value: true, ...PROP_BOOLEAN }],
    ['showpreview', { value: false, ...PROP_BOOLEAN }],
    ['tabindex', { value: 0, ...PROP_NUMBER }]
]);
const registerProps = () => {
    register('wm-richtexteditor', richTextProps);
    registerFormWidget(FormWidgetType.RICHTEXT, new Map(richTextProps));
};

const _c0 = ["wmRichTextEditor", ""];
function RichTextEditorComponent_div_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "div", 3);
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext();
    i0.ɵɵproperty("innerHTML", ctx_r0.proxyModel, i0.ɵɵsanitizeHtml);
} }
const WIDGET_INFO = { widgetType: 'wm-richtexteditor', hostClass: 'app-richtexteditor clearfix' };
const getChangeEvt = () => {
    let changeEvt;
    // for IE the event constructor doesn't work so use the createEvent proto
    if (typeof (Event) === 'function') {
        changeEvt = new Event('change');
    }
    else {
        changeEvt = document.createEvent('Event');
        changeEvt.initEvent('change', true, true);
    }
    return changeEvt;
};
const overrideSummerNote = () => {
    if (!$.summernote.__overidden) {
        // override summernote methods
        const origFn = $.summernote.ui_template().button.bind($.summernote);
        $.summernote.ui_template.button = (...args) => {
            const retVal = origFn(...args);
            const origCallback = retVal.callback;
            retVal.callback = ($node, options) => {
                // add bs3 btn class to the buttons
                $node.addClass('btn');
                return origCallback($node, options);
            };
            return retVal;
        };
        $.summernote.__overidden = true;
    }
};
class RichTextEditorComponent extends BaseFormCustomComponent {
    static { this.initializeProps = registerProps(); }
    get htmlcontent() {
        return this.performEditorOperation('code');
    }
    // @ts-ignore
    get datavalue() {
        return this.htmlcontent;
    }
    // @ts-ignore
    set datavalue(nv) {
        if (nv !== undefined && nv !== null) {
            this.$hiddenInputEle.val(nv);
            this.performEditorOperation('reset');
            this.performEditorOperation('code', nv);
        }
    }
    constructor(inj, sanitizePipe, ngZone, explicitContext) {
        super(inj, WIDGET_INFO, explicitContext);
        this.sanitizePipe = sanitizePipe;
        this.ngZone = ngZone;
        this._operationStack = [];
        this.isEditorLoaded = false;
        this.EDITOR_DEFAULT_OPTIONS = {
            toolbar: [
                // [groupName, [list of button]]
                ['misc', ['undo', 'redo']],
                ['style', ['style']],
                ['fontname', ['fontname']],
                ['fontsize', ['fontsize']],
                ['height', ['height']],
                ['style', ['bold', 'italic', 'underline', 'clear']],
                ['font', ['strikethrough', 'superscript', 'subscript']],
                ['color', ['color']],
                ['insert', ['table', 'picture', 'link', 'video', 'hr']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['misc', ['codeview', 'fullscreen', 'help']]
            ],
            callbacks: {
                onInit: () => {
                    this.isEditorLoaded = true;
                    if (this._operationStack.length) {
                        this._operationStack.forEach(operationParam => {
                            const key = Array.from(operationParam.keys())[0], val = operationParam.get(key);
                            this.performEditorOperation(key, val);
                        });
                        this._operationStack = [];
                    }
                },
                onChange: (contents, editable) => {
                    this.proxyModel = this.sanitizePipe.transform(contents, SecurityContext.HTML);
                    this.invokeOnChange(contents, getChangeEvt(), true);
                    this.invokeOnTouched();
                }
            },
            fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Merriweather'],
            placeholder: 'write here...',
            minHeight: 100,
            disableResizeEditor: true
        };
        styler(this.nativeElement, this, APPLY_STYLES_TYPE.CONTAINER, ['height']);
        overrideSummerNote();
    }
    ngOnInit() {
        this.$richTextEditor = $(this.nativeElement.querySelector('[richTextEditor]'));
        this.$hiddenInputEle = $(this.nativeElement.querySelector('input.model-holder'));
        super.ngOnInit();
        this.initEditor();
        $('.note-editable').attr('aria-label', 'textbox');
    }
    initEditor() {
        this.ngZone.runOutsideAngular(() => {
            this.invokeEventCallback('beforerender', { '$event': {} });
            this.$richTextEditor.summernote(this.EDITOR_DEFAULT_OPTIONS);
        });
    }
    getDefaultOptions() {
        return this.EDITOR_DEFAULT_OPTIONS;
    }
    getLib() {
        return 'summernote';
    }
    overrideDefaults(options) {
        extend(this.EDITOR_DEFAULT_OPTIONS, options);
    }
    onPropertyChange(key, nv, ov) {
        if (key === 'placeholder') {
            this.performEditorOperation('placeholder', nv);
        }
        else if (key === 'disabled' || key === 'readonly') {
            this.performEditorOperation(nv ? 'disable' : 'enable');
        }
        else {
            super.onPropertyChange(key, nv, ov);
        }
    }
    onStyleChange(key, nv, ov) {
        if (key === 'height') {
            this.performEditorOperation('height', nv);
        }
    }
    performEditorOperation(key, value) {
        if (this.isEditorLoaded) {
            if (key === 'height') {
                setCSS(this.nativeElement.querySelector('div.note-editable'), key, value, true);
            }
            else if (key === 'placeholder') {
                setAttr(this.nativeElement, key, value);
                setHtml(this.nativeElement.querySelector('div.note-placeholder'), value, true);
            }
            else {
                // if editor content is empty then summernote('code') is returning empty p tags like <p></br></p>. So checking for empty and returning undefined.
                if (arguments.length === 1 && key === 'code' && this.$richTextEditor.summernote('isEmpty')) {
                    const content = this.$richTextEditor.summernote('code');
                    return content === '' ? content : undefined;
                }
                return this.$richTextEditor.summernote(key, value);
            }
        }
        else {
            const op = new Map();
            op.set(key, value);
            this._operationStack.push(op);
            return;
        }
    }
    getCurrentPosition() {
        return this.performEditorOperation('createRange');
    }
    undo() {
        this.performEditorOperation('undo');
    }
    focus() {
        this.performEditorOperation('focus');
    }
    ngOnDestroy() {
        this.performEditorOperation('destroy');
        super.ngOnDestroy();
    }
    static { this.ɵfac = function RichTextEditorComponent_Factory(t) { return new (t || RichTextEditorComponent)(i0.ɵɵdirectiveInject(i0.Injector), i0.ɵɵdirectiveInject(i1.SanitizePipe), i0.ɵɵdirectiveInject(i0.NgZone), i0.ɵɵdirectiveInject('EXPLICIT_CONTEXT', 8)); }; }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: RichTextEditorComponent, selectors: [["div", "wmRichTextEditor", ""]], exportAs: ["wmRichTextEditor"], features: [i0.ɵɵProvidersFeature([
                provideAs(RichTextEditorComponent, NG_VALUE_ACCESSOR, true),
                provideAsWidgetRef(RichTextEditorComponent)
            ]), i0.ɵɵInheritDefinitionFeature], attrs: _c0, decls: 3, vars: 2, consts: [["richTextEditor", ""], ["class", "ta-preview", 3, "innerHTML", 4, "ngIf"], ["hidden", "", 1, "model-holder", 3, "disabled"], [1, "ta-preview", 3, "innerHTML"]], template: function RichTextEditorComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelement(0, "div", 0);
            i0.ɵɵtemplate(1, RichTextEditorComponent_div_1_Template, 1, 1, "div", 1);
            i0.ɵɵelement(2, "input", 2);
        } if (rf & 2) {
            i0.ɵɵadvance();
            i0.ɵɵproperty("ngIf", ctx.showpreview);
            i0.ɵɵadvance();
            i0.ɵɵproperty("disabled", ctx.disabled);
        } }, dependencies: [i2.NgIf], encapsulation: 2 }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(RichTextEditorComponent, [{
        type: Component,
        args: [{ selector: 'div[wmRichTextEditor]', providers: [
                    provideAs(RichTextEditorComponent, NG_VALUE_ACCESSOR, true),
                    provideAsWidgetRef(RichTextEditorComponent)
                ], exportAs: 'wmRichTextEditor', template: "<div richTextEditor></div>\n<div [innerHTML]=\"proxyModel\" class=\"ta-preview\" *ngIf=\"showpreview\"></div>\n<input class=\"model-holder\" [disabled]=\"disabled\" hidden>\n" }]
    }], () => [{ type: i0.Injector }, { type: i1.SanitizePipe }, { type: i0.NgZone }, { type: undefined, decorators: [{
                type: Inject,
                args: ['EXPLICIT_CONTEXT']
            }, {
                type: Optional
            }] }], null); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(RichTextEditorComponent, { className: "RichTextEditorComponent", filePath: "rich-text-editor.component.ts", lineNumber: 59 }); })();

const components = [
    RichTextEditorComponent
];
class RichTextEditorModule {
    static { this.ɵfac = function RichTextEditorModule_Factory(t) { return new (t || RichTextEditorModule)(); }; }
    static { this.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: RichTextEditorModule }); }
    static { this.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [CommonModule,
            WmComponentsModule] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(RichTextEditorModule, [{
        type: NgModule,
        args: [{
                imports: [
                    CommonModule,
                    WmComponentsModule
                ],
                declarations: [...components],
                exports: [...components]
            }]
    }], null, null); })();
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(RichTextEditorModule, { declarations: [RichTextEditorComponent], imports: [CommonModule,
        WmComponentsModule], exports: [RichTextEditorComponent] }); })();

/**
 * Generated bundle index. Do not edit.
 */

export { RichTextEditorComponent, RichTextEditorModule };
//# sourceMappingURL=index.mjs.map
