import * as i0 from '@angular/core';
import { Component, Attribute, Inject, Optional, ContentChild, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PROP_STRING, PROP_BOOLEAN, register, StylableComponent, styler, provideAsWidgetRef, WmComponentsModule } from '@wm/components/base';
import { debounceTime } from 'rxjs/operators';
import * as i1 from '@wm/core';
import { $appDigest, getClonedObject, isDefined, triggerFn } from '@wm/core';
import { TableComponent } from '@wm/components/data/table';

const registerProps = () => {
    register('wm-livetable', new Map([
        ['class', PROP_STRING],
        ['formlayout', PROP_STRING],
        ['name', PROP_STRING],
        ['show', { value: true, ...PROP_BOOLEAN }],
    ]));
};

const _c0 = ["wmLiveTable", ""];
const _c1 = ["*"];
const DEFAULT_CLS = 'app-livegrid';
const WIDGET_CONFIG = { widgetType: 'wm-livetable', hostClass: DEFAULT_CLS };
class LiveTableComponent extends StylableComponent {
    static { this.initializeProps = registerProps(); }
    constructor(inj, elRef, cdr, dialogService, app, layoutType, dialogId, explicitContext) {
        super(inj, WIDGET_CONFIG, explicitContext);
        this.dialogService = dialogService;
        this.app = app;
        this.$queue = [];
        this.tableOptions = {
            'multiselect': false,
            'setGridEditMode': ''
        };
        styler(this.nativeElement, this);
        if (layoutType === 'dialog') {
            this.isLayoutDialog = true;
            this.dialogId = dialogId;
        }
    }
    ngAfterContentInit() {
        super.ngAfterContentInit();
        if (this.table) {
            this.table._liveTableParent = this;
            this.table.datagridElement.datatable('option', this.tableOptions);
            this.table.selectedItemChange$
                .pipe(debounceTime(250))
                .subscribe(this.onSelectedItemChange.bind(this));
            if (!this.isLayoutDialog && !this.form) {
                this.table.datagridElement.datatable('option', {
                    'beforeRowUpdate': () => {
                        this.showErrorMessage();
                    },
                    'beforeRowDelete': () => {
                        this.showErrorMessage();
                    },
                    'beforeRowInsert': () => {
                        this.showErrorMessage();
                    }
                });
            }
        }
    }
    openDialog() {
        this.dialogService.open(this.dialogId, this.viewParent);
        $appDigest();
    }
    closeDialog() {
        this.dialogService.close(this.dialogId, this.viewParent);
    }
    focusFirstInput() {
        const $firstInput = $(this.form.$element).find('input').first();
        $firstInput.focus();
        $firstInput.select();
    }
    onDialogOpen() {
        this.focusFirstInput();
    }
    setFormData(val) {
        if (!this.form.isDestroyed) {
            this.form.getWidget().formdata = val;
        }
    }
    _addNewRow() {
        this.form.isSelected = true;
        this.setFormData('');
        this.form.new();
        if (this.isLayoutDialog) {
            this.onDialogOpen();
        }
    }
    addNewRow() {
        if (this.isLayoutDialog) {
            this.openDialog();
            this.$queue.push(this._addNewRow.bind(this));
            return;
        }
        this._addNewRow();
    }
    _updateRow(row, eventName) {
        this.setFormData(row);
        this.form.isSelected = true;
        this.form.edit();
        if (this.isLayoutDialog) {
            this.form.isUpdateMode = (eventName === 'dblclick') ? this.form.updateMode : true;
            this.onDialogOpen();
        }
    }
    updateRow(row, eventName) {
        if (this.isLayoutDialog) {
            this.openDialog();
            this.$queue.push(this._updateRow.bind(this, row, eventName));
            return;
        }
        this._updateRow(row, eventName);
    }
    onSelectedItemChange(newValue) {
        let rowData;
        if (!this.form || !this.table) {
            return;
        }
        if (newValue && newValue.length > 0 && !this.form.isSelected) {
            this.form.isSelected = true;
        }
        /*Update the rowdata of only that grid form that is associated with the specific grid on which row selection is being performed...
         * Since both the grid & gridform are associated with the same "parentgrid", match the same*/
        if (newValue && newValue.length > 0) {
            if (this.table.multiselect) {
                rowData = newValue[0];
            }
            else {
                rowData = newValue[newValue.length - 1];
            }
            this.setFormData(getClonedObject(rowData));
            /*If the form is already in update mode, call the form update function*/
            if (this.form.isUpdateMode) {
                this.form.edit();
            }
        }
        else {
            this.form.isSelected = false;
            this.setFormData('');
            this.form.clearData();
        }
    }
    onCancel() {
        this.form.isUpdateMode = false;
        if (this.isLayoutDialog) {
            this.closeDialog();
        }
    }
    onResult(operation, response, newForm, updateMode) {
        this.form.isUpdateMode = isDefined(updateMode) ? updateMode : newForm ? true : false;
        switch (operation) {
            case 'insert':
                if (this.table.gridOptions.isNavTypeScrollOrOndemand()) {
                    this.table.isNewRowInserted = true;
                }
                if (newForm) {
                    /*if new form is to be shown after insert, skip the highlight of the row*/
                    this.table.gridfirstrowselect = false;
                    this.table.initiateSelectItem(this.table.getNavigationTargetBySortInfo(), response, true);
                }
                else {
                    /*The new row would always be inserted at the end of all existing records. Hence navigate to the last page and highlight the inserted row.*/
                    this.table.initiateSelectItem(this.table.getNavigationTargetBySortInfo(), response);
                }
                break;
            case 'update':
                /*The updated row would be found in the current page itself. Hence simply highlight the row in the current page.*/
                if (newForm) {
                    this.table.gridfirstrowselect = false;
                    this.table.initiateSelectItem('current', response, true);
                }
                else {
                    this.table.initiateSelectItem('current', response);
                }
                break;
            case 'delete':
                this.table.onRecordDelete();
                break;
        }
        this.table.updateVariable();
        if (this.isLayoutDialog) {
            /*if new form is to be shown after update or insert, don't close the dialog*/
            if (newForm) {
                if (operation === 'insert') {
                    this.form.new();
                }
                else if (operation === 'update') {
                    this.form.edit();
                }
            }
            else {
                this.closeDialog();
            }
        }
    }
    showErrorMessage() {
        this.app.notifyApp(this.appLocale.LABEL_ACCESS_DENIED, 'error');
    }
    // In dialog mode, on form render call the queued functions
    onFormReady(form) {
        this.form = form;
        setTimeout(() => {
            triggerFn(this.$queue.pop());
        });
    }
    static { this.ɵfac = function LiveTableComponent_Factory(t) { return new (t || LiveTableComponent)(i0.ɵɵdirectiveInject(i0.Injector), i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef), i0.ɵɵdirectiveInject(i1.AbstractDialogService), i0.ɵɵdirectiveInject(i1.App), i0.ɵɵinjectAttribute('formlayout'), i0.ɵɵinjectAttribute('dialogid'), i0.ɵɵdirectiveInject('EXPLICIT_CONTEXT', 8)); }; }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: LiveTableComponent, selectors: [["", "wmLiveTable", ""]], contentQueries: function LiveTableComponent_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) {
            i0.ɵɵcontentQuery(dirIndex, TableComponent, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.table = _t.first);
        } }, features: [i0.ɵɵProvidersFeature([
                provideAsWidgetRef(LiveTableComponent)
            ]), i0.ɵɵInheritDefinitionFeature], attrs: _c0, ngContentSelectors: _c1, decls: 1, vars: 0, template: function LiveTableComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵprojectionDef();
            i0.ɵɵprojection(0);
        } }, encapsulation: 2 }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(LiveTableComponent, [{
        type: Component,
        args: [{ selector: '[wmLiveTable]', providers: [
                    provideAsWidgetRef(LiveTableComponent)
                ], template: "<ng-content></ng-content>" }]
    }], () => [{ type: i0.Injector }, { type: i0.ElementRef }, { type: i0.ChangeDetectorRef }, { type: i1.AbstractDialogService }, { type: i1.App }, { type: undefined, decorators: [{
                type: Attribute,
                args: ['formlayout']
            }] }, { type: undefined, decorators: [{
                type: Attribute,
                args: ['dialogid']
            }] }, { type: undefined, decorators: [{
                type: Inject,
                args: ['EXPLICIT_CONTEXT']
            }, {
                type: Optional
            }] }], { table: [{
            type: ContentChild,
            args: [TableComponent]
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(LiveTableComponent, { className: "LiveTableComponent", filePath: "live-table.component.ts", lineNumber: 33 }); })();

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

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

export { LiveTableComponent, LiveTableModule };
//# sourceMappingURL=index.mjs.map
