import { Component, OnInit } from "@angular/core";
import { FormlyFieldInput } from "@ngx-formly/bootstrap/input";


@Component({
    selector: 'formly-richtext-type',
    template: `        
        <ng-template #labelTemplate>
            <label *ngIf="props.label && props.hideLabel !== true" [attr.for]="id" class="form-label">
                {{ props.label }}
                <span *ngIf="props.required && props.hideRequiredMarker !== true" aria-hidden="true">*</span>
            </label>
        </ng-template>
        <ng-template #inputTemplate>
            <editor *ngIf="! this.field.props.disabled"
                 apiKey="mjk3fhupxy3pitud9iyfqse231zpuuosqedmlgydrjx6mjlo"
                 [init]="getInitConfig()"
                 [formControl]="formControl"
                 [class.is-invalid]="showError"
                 [formlyAttributes]="field"
                 [inline]="false"
                 (onGetContent)="onGetContent($event)"
                 (onBeforeAddUndo)="onBeforeAddUndo($event)"
            ></editor>
            <div *ngIf="this.field.props.disabled" [innerHTML]="formControl.value" class="form-control contract-body">
            </div>
        </ng-template>
        
        <ng-container *ngIf="props.labelPosition !== 'floating'">
            <ng-container [ngTemplateOutlet]="labelTemplate"></ng-container>
        </ng-container>
        <ng-container [ngTemplateOutlet]="inputTemplate"></ng-container>
        <div *ngIf="showError" class="invalid-feedback" [style.display]="'block'">
            <formly-validation-message [field]="field"></formly-validation-message>
        </div>
        <small *ngIf="props.description" class="form-text text-muted">{{ props.description }}</small>
    `,
})
export class RichtextTypeComponent extends FormlyFieldInput implements OnInit {
    multiline = true;

    init_common = {
        statusbar: false,
        autoresize_bottom_margin: 0,
        body_class: "contract-body",
        content_style: ".contract-body { font-family: 'Century Schoolbook', 'sans-serif' }",
        entity_encoding: 'raw',
        paste_preprocess: function (plugin: any, args: any) {
            console.log(args.content)
            let container = document.createElement('div');
            container.innerHTML = args.content.trim();
            cleanPastedElement(container)
            console.log(container.innerHTML);
            args.content = container.innerHTML;
        }
    }

    init_multiline = {
        plugins: 'lists image imagetools table code searchreplace paste autoresize',
        menubar: 'edit insert format tools table',
        menu: {
            edit: { title: 'Edit', items: 'undo redo | cut copy paste | selectall | searchreplace' },
            insert: { title: 'Insert', items: 'image link media template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime' },
            format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | removeformat' },
            tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | code wordcount' },
            table: { title: 'Table', items: 'inserttable | cell row column | tableprops deletetable' }
        },
        toolbar: 'undo redo | styleselect | bold italic underline | alignleft aligncenter alignright alignjustify | outdent indent bullist numlist | table image',
    }

    init_singleline = {
        plugins: 'paste autoresize',
        menubar: '',
        toolbar: 'undo redo | bold italic underline',
    }

    ngOnInit() {
        if (this.props.hasOwnProperty('multiline')) {
            // @ts-ignore
            this.multiline = this.props['multiline']
        }
    }

    getInitConfig(): any {
        return {...this.init_common, ...( this.multiline ? this.init_multiline : this.init_singleline)};
    }

    onGetContent(param: any) {
        if (!this.multiline) {
            const result = param.event.content.match(/<p>(.*)<\/p>/);
            if (result) {
                param.event.content = result[1];
            }
        }
    }

    onBeforeAddUndo(param: any) {
        if (!this.multiline) {
            if (param.event.level.content.indexOf('</p><p>') > -1) {
                param.event.preventDefault()
                param.editor.setContent(param.event.level.content.replace('</p><p>', ''));
            }
        }
    }
}

function cleanPastedElement(htmlElement: HTMLElement): string {
    if (! htmlElement.innerHTML) {
        return "";
    }

    let innerHtml = ""
    for(let i = 0; i < htmlElement.childNodes.length; i++){
        const childNode = htmlElement.childNodes[i] as HTMLElement
        if (childNode.nodeName == "#text") {
            innerHtml += childNode.nodeValue;
        } else {
            innerHtml += cleanPastedElement(childNode);
        }
    }
    htmlElement.innerHTML = innerHtml

    if (htmlElement.tagName == "SPAN") {
        let text = htmlElement.innerHTML
        const style = htmlElement.style

        if (style.fontWeight == "700") {
            let strong = document.createElement('b');
            strong.innerHTML = text
            text = strong.outerHTML;
        }
        if (style.textDecoration == "underline") {
            let underline = document.createElement('u');
            underline.innerHTML = text;
            text = underline.outerHTML;
        }
        if (style.fontStyle == "italic") {
            let italic = document.createElement('em');
            italic.innerHTML = text;
            text = italic.outerHTML;
        }

        return text;
    }

    htmlElement.style.removeProperty("line-height")
    htmlElement.style.removeProperty("margin")

    return htmlElement.outerHTML
}
