(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('@wm/components/base'), require('rxjs/operators'), require('@wm/core'), require('@wm/components/data/table')) :
    typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@angular/common', '@wm/components/base', 'rxjs/operators', '@wm/core', '@wm/components/data/table'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.wm = global.wm || {}, global.wm.components = global.wm.components || {}, global.wm.components.data = global.wm.components.data || {}, global.wm.components.data.livetable = {}), global.ng.core, global.ng.common, global.wm.components.base, global.rxjs.operators, global.wm.core, global.wm.components.data.table));
})(this, (function (exports, i0, common, base, operators, i1, table) { 'use strict';

    function _interopNamespaceDefault(e) {
        var n = Object.create(null);
        if (e) {
            Object.keys(e).forEach(function (k) {
                if (k !== 'default') {
                    var d = Object.getOwnPropertyDescriptor(e, k);
                    Object.defineProperty(n, k, d.get ? d : {
                        enumerable: true,
                        get: function () { return e[k]; }
                    });
                }
            });
        }
        n.default = e;
        return Object.freeze(n);
    }

    var i0__namespace = /*#__PURE__*/_interopNamespaceDefault(i0);
    var i1__namespace = /*#__PURE__*/_interopNamespaceDefault(i1);

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

    const _c0 = ["wmLiveTable", ""];
    const _c1 = ["*"];
    const DEFAULT_CLS = 'app-livegrid';
    const WIDGET_CONFIG = { widgetType: 'wm-livetable', hostClass: DEFAULT_CLS };
    class LiveTableComponent extends base.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': ''
            };
            base.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(operators.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);
            i1.$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(i1.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 = i1.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(() => {
                i1.triggerFn(this.$queue.pop());
            });
        }
        static { this.ɵfac = function LiveTableComponent_Factory(t) { return new (t || LiveTableComponent)(i0__namespace.ɵɵdirectiveInject(i0__namespace.Injector), i0__namespace.ɵɵdirectiveInject(i0__namespace.ElementRef), i0__namespace.ɵɵdirectiveInject(i0__namespace.ChangeDetectorRef), i0__namespace.ɵɵdirectiveInject(i1__namespace.AbstractDialogService), i0__namespace.ɵɵdirectiveInject(i1__namespace.App), i0__namespace.ɵɵinjectAttribute('formlayout'), i0__namespace.ɵɵinjectAttribute('dialogid'), i0__namespace.ɵɵdirectiveInject('EXPLICIT_CONTEXT', 8)); }; }
        static { this.ɵcmp = /*@__PURE__*/ i0__namespace.ɵɵdefineComponent({ type: LiveTableComponent, selectors: [["", "wmLiveTable", ""]], contentQueries: function LiveTableComponent_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) {
                i0__namespace.ɵɵcontentQuery(dirIndex, table.TableComponent, 5);
            } if (rf & 2) {
                let _t;
                i0__namespace.ɵɵqueryRefresh(_t = i0__namespace.ɵɵloadQuery()) && (ctx.table = _t.first);
            } }, features: [i0__namespace.ɵɵProvidersFeature([
                    base.provideAsWidgetRef(LiveTableComponent)
                ]), i0__namespace.ɵɵInheritDefinitionFeature], attrs: _c0, ngContentSelectors: _c1, decls: 1, vars: 0, template: function LiveTableComponent_Template(rf, ctx) { if (rf & 1) {
                i0__namespace.ɵɵprojectionDef();
                i0__namespace.ɵɵprojection(0);
            } }, encapsulation: 2 }); }
    }
    (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0__namespace.ɵsetClassMetadata(LiveTableComponent, [{
            type: i0.Component,
            args: [{ selector: '[wmLiveTable]', providers: [
                        base.provideAsWidgetRef(LiveTableComponent)
                    ], template: "<ng-content></ng-content>" }]
        }], () => [{ type: i0__namespace.Injector }, { type: i0__namespace.ElementRef }, { type: i0__namespace.ChangeDetectorRef }, { type: i1__namespace.AbstractDialogService }, { type: i1__namespace.App }, { type: undefined, decorators: [{
                    type: i0.Attribute,
                    args: ['formlayout']
                }] }, { type: undefined, decorators: [{
                    type: i0.Attribute,
                    args: ['dialogid']
                }] }, { type: undefined, decorators: [{
                    type: i0.Inject,
                    args: ['EXPLICIT_CONTEXT']
                }, {
                    type: i0.Optional
                }] }], { table: [{
                type: i0.ContentChild,
                args: [table.TableComponent]
            }] }); })();
    (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0__namespace.ɵ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__namespace.ɵɵdefineNgModule({ type: LiveTableModule }); }
        static { this.ɵinj = /*@__PURE__*/ i0__namespace.ɵɵdefineInjector({ imports: [common.CommonModule,
                base.WmComponentsModule] }); }
    }
    (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0__namespace.ɵsetClassMetadata(LiveTableModule, [{
            type: i0.NgModule,
            args: [{
                    imports: [
                        common.CommonModule,
                        base.WmComponentsModule
                    ],
                    declarations: [...components],
                    exports: [...components]
                }]
        }], null, null); })();
    (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0__namespace.ɵɵsetNgModuleScope(LiveTableModule, { declarations: [LiveTableComponent], imports: [common.CommonModule,
            base.WmComponentsModule], exports: [LiveTableComponent] }); })();

    exports.LiveTableComponent = LiveTableComponent;
    exports.LiveTableModule = LiveTableModule;

}));
