import {ICellEditorAngularComp} from 'ag-grid-angular';
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
import {ICellEditorParams} from 'ag-grid-community';
import {ModalController} from '@ionic/angular';
import {WysiwygModalComponent} from './wysiwyg-modal.component';

@Component({
    selector: 'cell-editor-wysiwyg',
    template: `<input #input [(ngModel)]="value" readonly>`,
    styles: [
        `input {
            width: 100%;
            border: 1px solid grey;
        }`
    ],
})
export class WysiwygEditorComponent implements ICellEditorAngularComp, AfterViewInit {
    private params: ICellEditorParams;
    public value: string;

    @ViewChild('input') input: ElementRef;

    constructor(
        protected modals: ModalController,
    ) { }

    agInit(params: ICellEditorParams): void {
        this.params = params;
        this.value = this.params.value;
    }

    getValue(): any {
        return this.value;
    }

    ngAfterViewInit(): void {
        setTimeout(() => {
            this.modals.create({
                component: WysiwygModalComponent,
                componentProps: {
                    title: this.params.colDef.headerName,
                    value: this.value,
                }
            }).then(modal => {
                modal.onDidDismiss().then(value => {
                    if ( typeof value.data === 'undefined' ) {
                        return;
                    }

                    this.value = String(value.data);
                    this.finishEdit();
                });

                const modalState = {
                    modal : true,
                    desc : 'WYSIWYG editor'
                };

                history.pushState(modalState, null);

                modal.present();
            });
        });
    }

    finishEdit() {
        this.params.stopEditing();
    }
}
