import { Component, EventEmitter, Inject, Input, IterableDiffers, Optional, Output, ViewChild } from '@angular/core';
import { NG_ASYNC_VALIDATORS, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgModel } from '@angular/forms';
import { ElementBase } from '../../base/element-base';
import { INPUT_FORMS_CONFIG } from '../../input-forms-config.constants';
import * as i0 from "@angular/core";
import * as i1 from "@angular/common";
import * as i2 from "@angular/forms";
import * as i3 from "../../../ui/directives/debounce.directive";
import * as i4 from "../../../ui/directives/click-outside.directive";
import * as i5 from "../../../ui/directives/auto-focus.directive";
import * as i6 from "ngx-bootstrap/tooltip";
import * as i7 from "../../../data-grid/data-grid.component";
import * as i8 from "../../../data-grid/directives/data-grid-templates.directive";
import * as i9 from "../input-validations/input-validations.component";
let identifier = 0;
export class InputDropdownGridComponent extends ElementBase {
    constructor(validators, asyncValidators, config, iterableDiffers) {
        super(validators, asyncValidators, config);
        this.config = config;
        this.iterableDiffers = iterableDiffers;
        this.clickOutsideEnabled = true;
        this.placeholder = 'Select...';
        this.searchPlaceholder = 'Search...';
        this.itemsPerPage = 5;
        this.maxSize = 5;
        this.showInfos = true;
        this.onChange = new EventEmitter();
        this.onSearch = new EventEmitter();
        this.identifier = `input-dropdown-grid-${identifier++}`;
        if (config.dropDown) {
            Object.assign(this, config.dropDown);
        }
        this._differData = this.iterableDiffers.find([]).create(null);
    }
    get data() {
        return this._data;
    }
    set data(value) {
        this._data = value;
        this.Init();
    }
    ngOnInit() {
        this.Init();
    }
    ngDoCheck() {
        let changesInData = this._differData.diff(this._data);
        if (changesInData || !this.modelInitialized || this.value != this._lastModelInitialized) {
            this.Init();
        }
    }
    Init() {
        this.clearSearch();
        if (!this.internalData || this.internalData.length == 0) {
            return;
        }
        if (this.value) {
            this.setSelectedItemByTheCurrentModelValue();
            this._lastModelInitialized = this.value;
        }
        else {
            this.selectedDisplayText = '';
            this._lastModelInitialized = undefined;
        }
        this.modelInitialized = true;
    }
    ToggleDropDown(event, value) {
        if (this.clickOutsideEnabled) {
            if ((value == false && !this.showDropdown) || (value == undefined && this.disabled))
                return;
            if (value == undefined) {
                if (this.showDropdown) {
                    this.setComboTouched();
                }
                this.showDropdown = !this.showDropdown;
            }
            else {
                if (!value && this.showDropdown) {
                    this.setComboTouched();
                }
                this.showDropdown = value;
            }
            this.clearSearch();
        }
        else {
            this.clickOutsideEnabled = true;
        }
    }
    Select(row) {
        if (this.disabled) {
            this.ToggleDropDown(null, false);
            return;
        }
        this.value = this.renderPropertyValue(this.valueProperty, row);
        this.onChange.emit(this.value);
        this.ToggleDropDown(null, false);
    }
    OnSearch() {
        if (this.lazyLoadedData) {
            this.onSearch.emit(this.search);
            return;
        }
        if (!this.search || this.search.length < 3) {
            this.clearSearchResults();
            return;
        }
        this.filterData();
    }
    OnPaginate() {
        this.clickOutsideEnabled = false;
    }
    ClearSelection(e) {
        this.value = null;
        this.selectedDisplayText = null;
        this.comboTouched = true;
        this.showDropdown = false;
        this.onChange.emit(this.value);
        if (e)
            e.stopPropagation();
    }
    OnComboPressed(event) {
        if (event.keyCode == 13) {
            this.ToggleDropDown(null);
            event.preventDefault();
        }
    }
    setSelectedItemByTheCurrentModelValue() {
        if (!this.value)
            return;
        let row = this.data.find(x => this.value == this.renderPropertyValue(this.valueProperty, x));
        if (row) {
            this.selectedDisplayText = this.renderPropertyValue(this.displayTextProperty, row);
        }
    }
    filterData() {
        this.internalData = this.data.filter(x => {
            for (let i = 0; i < this.columns.length; i++) {
                let columnData = '';
                let value = '';
                if (this.columns[i].data) {
                    columnData = this.renderPropertyValue(this.columns[i].data, x);
                }
                if (this.columns[i].render != undefined) {
                    value = this.columns[i].render(x, columnData, i);
                }
                else {
                    value = columnData;
                }
                if (value && value.toString().toUpperCase().indexOf(this.search.toUpperCase()) >= 0) {
                    return true;
                }
            }
            return false;
        });
    }
    clearSearch() {
        this.search = '';
        this.clearSearchResults();
    }
    clearSearchResults() {
        this.internalData = Object.assign([], this.data);
    }
    setComboTouched() {
        this.comboTouched = true;
    }
    renderPropertyValue(propertyPath, object) {
        let parts = propertyPath.split(".");
        let property = object || {};
        for (let i = 0; i < parts.length; i++) {
            if (!property) {
                return null;
            }
            property = property[parts[i]];
        }
        return property;
    }
}
InputDropdownGridComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: InputDropdownGridComponent, deps: [{ token: NG_VALIDATORS, optional: true }, { token: NG_ASYNC_VALIDATORS, optional: true }, { token: INPUT_FORMS_CONFIG }, { token: i0.IterableDiffers }], target: i0.ɵɵFactoryTarget.Component });
InputDropdownGridComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: InputDropdownGridComponent, selector: "input-dropdown-grid", inputs: { placeholder: "placeholder", searchPlaceholder: "searchPlaceholder", displayTextProperty: "displayTextProperty", valueProperty: "valueProperty", columns: "columns", lazyLoadedData: "lazyLoadedData", itemsPerPage: "itemsPerPage", maxSize: "maxSize", showInfos: "showInfos", data: "data" }, outputs: { onChange: "onChange", onSearch: "onSearch" }, providers: [{
            provide: NG_VALUE_ACCESSOR,
            useExisting: InputDropdownGridComponent,
            multi: true
        }], viewQueries: [{ propertyName: "model", first: true, predicate: NgModel, descendants: true, static: true }], usesInheritance: true, ngImport: i0, template: "<div [id]=\"identifier\" class=\"ui-dropdown-grid\">\n  <label *ngIf=\"label\">\n    {{label}}\n    <span class=\"required-symbol\" *ngIf=\"isRequired\"> *</span>\n    <i class=\"fa fa-question-circle ml-2\" tooltip=\"{{help}}\" container=\"body\" *ngIf=\"help\"></i>\n  </label>\n\n  <input type=\"hidden\" [(ngModel)]=\"value\" />\n  <div class=\"combobox d-flex align-items-center\" \n    [ngClass]=\"{\n      'has-validations': showValidations,\n      'open': showDropdown, \n      'disabled': disabled,\n      'is-valid': !showDropdown && !disabled && comboTouched && (!isRequired || value),\n      'is-invalid': !showDropdown && !disabled && comboTouched && isRequired && !value\n    }\"\n    (click)=\"ToggleDropDown($event)\" (keyup)=\"OnComboPressed($event)\" tabindex=\"0\">\n\n    <span class=\"mr-auto text-truncate\">{{selectedDisplayText || placeholder}}</span>\n    <i class=\"fa fa-times btn-clear-selection\" *ngIf=\"value && !disabled\" (click)=\"ClearSelection($event)\"></i>\n    <i class=\"fa\" [ngClass]=\"{'fa-caret-down': !showDropdown, 'fa-caret-up': showDropdown}\"></i>\n  </div>\n\n  <div class=\"dropdown-options shadow fadeInDown\" *ngIf=\"showDropdown\" (clickOutside)=\"ToggleDropDown($event, false)\">\n    <div class=\"options-container\">\n      <div class=\"toolbar d-flex align-items-center\">\n        <input type=\"text\" auto-focus\n          class=\"form-control\" \n          name=\"{{identifier}}-search\" \n          [(ngModel)]=\"search\" \n          placeholder=\"{{searchPlaceholder}}\"\n          debounce (callback)=\"OnSearch()\" />\n      </div>\n\n      <div class=\"p-2\">\n        <datagrid \n          [data]=\"internalData\" \n          [columns]=\"columns\" \n          [showActionsColumn]=\"true\"\n          [initialColumnToSort]=\"0\"          \n          [itemsPerPage]=\"itemsPerPage\"\n          [maxSize]=\"maxSize\"\n          [showInfos]=\"showInfos\"          \n          actionsColumnWidth=\"60px\"\n          (OnPaginate)=\"OnPaginate()\">\n          <ng-template actions-column let-row=\"row\" let-rowIndex=\"rowIndex\">\n            <button class=\"btn btn-outline-primary btn-sm\" (click)=\"Select(row)\"><i class=\"fa fa-external-link\"></i></button>\n          </ng-template>\n        </datagrid>\n      </div>\n    </div>\n  </div>\n</div>\n\n<input-validations\n  *ngIf=\"showValidations && !disabled && comboTouched && (invalid | async)\"\n  [messages]=\"failures | async\">\n</input-validations>\n\n<small class=\"text-muted\" *ngIf=\"description\">{{description}}</small>\n", styles: ["@keyframes fadeInDown{0%{opacity:0;transform:translate3d(0,-5%,0)}to{opacity:1;transform:translateZ(0)}}.fadeInDown{animation-name:fadeInDown;animation-duration:.35s;animation-fill-mode:both}.ui-dropdown-grid{position:relative}.ui-dropdown-grid *{-webkit-user-select:none;user-select:none}.ui-dropdown-grid>.combobox{outline:none;background-color:#fff;padding:.375rem .4rem .375rem .75rem;border:1px solid #ced4da;border-radius:.25rem}.ui-dropdown-grid>.combobox>span{color:#6c757d;font-size:1rem;line-height:1.5}.ui-dropdown-grid>.combobox>i{color:#495057;font-size:14px;margin-left:10px}.ui-dropdown-grid>.combobox.open{border-radius:.25rem .25rem 0 0}.ui-dropdown-grid>.combobox.disabled{background-color:#e9ecef;border-color:#ced4da}.ui-dropdown-grid>.combobox.has-validations.is-invalid{border-color:#dc3545}.ui-dropdown-grid>.combobox.has-validations.is-invalid.open{box-shadow:0 0 0 .2rem #dc354540}.ui-dropdown-grid>.combobox.has-validations.is-valid{border-color:#28a745}.ui-dropdown-grid>.combobox.has-validations.is-valid.open{box-shadow:0 0 0 .2rem #28a74540}.ui-dropdown-grid>.dropdown-options{background-color:#fff;border:1px solid #ced4da;border-radius:0 0 .25rem .25rem;position:absolute;top:100%;left:0;width:100%;z-index:20;margin-top:-1px;min-width:300px}.ui-dropdown-grid>.dropdown-options>.options-container{display:inherit;position:initial;font-family:inherit;background-color:inherit;box-shadow:none;height:auto;width:auto;color:inherit;font-size:inherit;letter-spacing:inherit;line-height:inherit;padding:inherit;border-radius:inherit}.ui-dropdown-grid>.dropdown-options .toolbar{padding:3px;border-bottom:1px solid #ced4da;background-color:#f8f9fa}.ui-dropdown-grid>.dropdown-options .toolbar input[type=text]{background-color:transparent;border:0;padding:.375rem .55rem;box-shadow:none!important}.ui-dropdown-grid>.dropdown-options .empty-results{font-style:italic;padding:12px;display:block;color:#6b6b6b}.btn-clear-selection{cursor:pointer;padding:8px 10px;margin:-5px 0 -5px -5px!important;border-radius:3px}.btn-clear-selection:hover{background-color:#e7e7e7}\n"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i2.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i3.DebounceDirective, selector: "[debounce]", inputs: ["delay"], outputs: ["callback", "arrowsCallback"] }, { kind: "directive", type: i4.ClickOutsideDirective, selector: "[clickOutside]", inputs: ["clickOutsideEnabled", "attachOutsideOnClick", "delayClickOutsideInit", "emitOnBlur", "exclude", "excludeBeforeClick", "clickOutsideEvents"], outputs: ["clickOutside"] }, { kind: "directive", type: i5.AutoFocusDirective, selector: "[auto-focus]" }, { kind: "directive", type: i6.TooltipDirective, selector: "[tooltip], [tooltipHtml]", inputs: ["containerClass", "tooltipAnimation", "tooltipFadeDuration", "isOpen", "tooltipHtml", "tooltip", "tooltipPlacement", "placement", "tooltipIsOpen", "tooltipEnable", "isDisabled", "tooltipAppendToBody", "container", "tooltipClass", "tooltipContext", "tooltipPopupDelay", "delay", "tooltipTrigger", "triggers", "adaptivePosition"], outputs: ["tooltipChange", "tooltipStateChanged", "onShown", "onHidden"], exportAs: ["bs-tooltip"] }, { kind: "component", type: i7.DataGridComponent, selector: "datagrid", inputs: ["debugMode", "tableId", "columns", "emptyResultsMessage", "infoMessage", "animated", "striped", "bordered", "hoverEffect", "responsive", "showCheckboxColumn", "showSelectAllCheckbox", "selectAllPages", "checkBoxMode", "showSummaries", "allowExports", "exportButtonLabel", "exportedFileName", "exportedExcelSheetName", "initialColumnToSort", "initialSortDirection", "mode", "totalItems", "itemsPerPage", "maxSize", "boundaryLinks", "directionLinks", "rotate", "showActionsColumn", "showInfos", "actionsColumnCaption", "actionsColumnWidth", "firstText", "previousText", "nextText", "lastText", "autoFitMode", "allowColumnResize", "allowColumnFilters", "allowColumnReorder", "fixedHeader", "minHeight", "maxHeight", "userPreferencesKey", "filterPlaceholder", "filterPlacement", "boundedExportCallback", "data"], outputs: ["OnSelectionChanged", "OnRowSelected", "OnRowRendered", "OnPaginate", "OnSort", "OnColumnFiltered"] }, { kind: "directive", type: i8.ActionsColumnDirective, selector: "[actions-column]" }, { kind: "component", type: i9.InputValidationsComponent, selector: "input-validations", inputs: ["messages"] }, { kind: "pipe", type: i1.AsyncPipe, name: "async" }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: InputDropdownGridComponent, decorators: [{
            type: Component,
            args: [{ selector: 'input-dropdown-grid', providers: [{
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: InputDropdownGridComponent,
                            multi: true
                        }], template: "<div [id]=\"identifier\" class=\"ui-dropdown-grid\">\n  <label *ngIf=\"label\">\n    {{label}}\n    <span class=\"required-symbol\" *ngIf=\"isRequired\"> *</span>\n    <i class=\"fa fa-question-circle ml-2\" tooltip=\"{{help}}\" container=\"body\" *ngIf=\"help\"></i>\n  </label>\n\n  <input type=\"hidden\" [(ngModel)]=\"value\" />\n  <div class=\"combobox d-flex align-items-center\" \n    [ngClass]=\"{\n      'has-validations': showValidations,\n      'open': showDropdown, \n      'disabled': disabled,\n      'is-valid': !showDropdown && !disabled && comboTouched && (!isRequired || value),\n      'is-invalid': !showDropdown && !disabled && comboTouched && isRequired && !value\n    }\"\n    (click)=\"ToggleDropDown($event)\" (keyup)=\"OnComboPressed($event)\" tabindex=\"0\">\n\n    <span class=\"mr-auto text-truncate\">{{selectedDisplayText || placeholder}}</span>\n    <i class=\"fa fa-times btn-clear-selection\" *ngIf=\"value && !disabled\" (click)=\"ClearSelection($event)\"></i>\n    <i class=\"fa\" [ngClass]=\"{'fa-caret-down': !showDropdown, 'fa-caret-up': showDropdown}\"></i>\n  </div>\n\n  <div class=\"dropdown-options shadow fadeInDown\" *ngIf=\"showDropdown\" (clickOutside)=\"ToggleDropDown($event, false)\">\n    <div class=\"options-container\">\n      <div class=\"toolbar d-flex align-items-center\">\n        <input type=\"text\" auto-focus\n          class=\"form-control\" \n          name=\"{{identifier}}-search\" \n          [(ngModel)]=\"search\" \n          placeholder=\"{{searchPlaceholder}}\"\n          debounce (callback)=\"OnSearch()\" />\n      </div>\n\n      <div class=\"p-2\">\n        <datagrid \n          [data]=\"internalData\" \n          [columns]=\"columns\" \n          [showActionsColumn]=\"true\"\n          [initialColumnToSort]=\"0\"          \n          [itemsPerPage]=\"itemsPerPage\"\n          [maxSize]=\"maxSize\"\n          [showInfos]=\"showInfos\"          \n          actionsColumnWidth=\"60px\"\n          (OnPaginate)=\"OnPaginate()\">\n          <ng-template actions-column let-row=\"row\" let-rowIndex=\"rowIndex\">\n            <button class=\"btn btn-outline-primary btn-sm\" (click)=\"Select(row)\"><i class=\"fa fa-external-link\"></i></button>\n          </ng-template>\n        </datagrid>\n      </div>\n    </div>\n  </div>\n</div>\n\n<input-validations\n  *ngIf=\"showValidations && !disabled && comboTouched && (invalid | async)\"\n  [messages]=\"failures | async\">\n</input-validations>\n\n<small class=\"text-muted\" *ngIf=\"description\">{{description}}</small>\n", styles: ["@keyframes fadeInDown{0%{opacity:0;transform:translate3d(0,-5%,0)}to{opacity:1;transform:translateZ(0)}}.fadeInDown{animation-name:fadeInDown;animation-duration:.35s;animation-fill-mode:both}.ui-dropdown-grid{position:relative}.ui-dropdown-grid *{-webkit-user-select:none;user-select:none}.ui-dropdown-grid>.combobox{outline:none;background-color:#fff;padding:.375rem .4rem .375rem .75rem;border:1px solid #ced4da;border-radius:.25rem}.ui-dropdown-grid>.combobox>span{color:#6c757d;font-size:1rem;line-height:1.5}.ui-dropdown-grid>.combobox>i{color:#495057;font-size:14px;margin-left:10px}.ui-dropdown-grid>.combobox.open{border-radius:.25rem .25rem 0 0}.ui-dropdown-grid>.combobox.disabled{background-color:#e9ecef;border-color:#ced4da}.ui-dropdown-grid>.combobox.has-validations.is-invalid{border-color:#dc3545}.ui-dropdown-grid>.combobox.has-validations.is-invalid.open{box-shadow:0 0 0 .2rem #dc354540}.ui-dropdown-grid>.combobox.has-validations.is-valid{border-color:#28a745}.ui-dropdown-grid>.combobox.has-validations.is-valid.open{box-shadow:0 0 0 .2rem #28a74540}.ui-dropdown-grid>.dropdown-options{background-color:#fff;border:1px solid #ced4da;border-radius:0 0 .25rem .25rem;position:absolute;top:100%;left:0;width:100%;z-index:20;margin-top:-1px;min-width:300px}.ui-dropdown-grid>.dropdown-options>.options-container{display:inherit;position:initial;font-family:inherit;background-color:inherit;box-shadow:none;height:auto;width:auto;color:inherit;font-size:inherit;letter-spacing:inherit;line-height:inherit;padding:inherit;border-radius:inherit}.ui-dropdown-grid>.dropdown-options .toolbar{padding:3px;border-bottom:1px solid #ced4da;background-color:#f8f9fa}.ui-dropdown-grid>.dropdown-options .toolbar input[type=text]{background-color:transparent;border:0;padding:.375rem .55rem;box-shadow:none!important}.ui-dropdown-grid>.dropdown-options .empty-results{font-style:italic;padding:12px;display:block;color:#6b6b6b}.btn-clear-selection{cursor:pointer;padding:8px 10px;margin:-5px 0 -5px -5px!important;border-radius:3px}.btn-clear-selection:hover{background-color:#e7e7e7}\n"] }]
        }], ctorParameters: function () { return [{ type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [NG_VALIDATORS]
                }] }, { type: undefined, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [NG_ASYNC_VALIDATORS]
                }] }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [INPUT_FORMS_CONFIG]
                }] }, { type: i0.IterableDiffers }]; }, propDecorators: { model: [{
                type: ViewChild,
                args: [NgModel, { static: true }]
            }], placeholder: [{
                type: Input
            }], searchPlaceholder: [{
                type: Input
            }], displayTextProperty: [{
                type: Input
            }], valueProperty: [{
                type: Input
            }], columns: [{
                type: Input
            }], lazyLoadedData: [{
                type: Input
            }], itemsPerPage: [{
                type: Input
            }], maxSize: [{
                type: Input
            }], showInfos: [{
                type: Input
            }], onChange: [{
                type: Output
            }], onSearch: [{
                type: Output
            }], data: [{
                type: Input,
                args: ['data']
            }] } });
//# sourceMappingURL=data:application/json;base64, 