import { EventEmitter, ElementRef, Renderer2, ViewChild, Output, Input, Component, forwardRef, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MultiLingualData } from '@rxweb/localization';
import { CommonModule } from '@angular/common';
import { RxHttp } from '@rxweb/http';

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var SelectModel = /** @class */ (function () {
    function SelectModel(key, value, active) {
        this.key = key;
        this.value = value;
        this.active = active;
    }
    return SelectModel;
}());
var RxSelectComponent = /** @class */ (function (_super) {
    __extends(RxSelectComponent, _super);
    function RxSelectComponent(elementRef, renderer) {
        var _this = _super.call(this) || this;
        _this.elementRef = elementRef;
        _this.renderer = renderer;
        _this.propagateChange = function () { };
        _this.inputDisabled = false;
        _this.isInValid = false;
        _this.dropIndex = 0;
        _this.isSpinner = false;
        _this.selectActive = false;
        _this.blur = new EventEmitter();
        _this.changed = new EventEmitter();
        _this.maxLength = 500;
        _this.selectPlaceholder = "";
        _this.showSelectItem = true;
        _this.focus = false;
        _this.autoComplete = false;
        _this.isObjectChanged = false;
        _this.mainSource = new Array();
        _this.dropSource = new Array();
        _this.element = elementRef.nativeElement;
        var placeholderText = MultiLingualData.get("global.control.rx-select.placeholder");
        if (_this.selectPlaceholder == "" && placeholderText)
            _this.selectPlaceholder = placeholderText;
        return _this;
    }
    RxSelectComponent_1 = RxSelectComponent;
    Object.defineProperty(RxSelectComponent.prototype, "source", {
        set: function (value) {
            if (value) {
                this.userSource = value;
                if (this.keyValueProps)
                    this.setMainSource(this.userSource);
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(RxSelectComponent.prototype, "text", {
        set: function (value) {
            if (value) {
                if (this.selectSearch && this.selectSearch.nativeElement)
                    this.selectSearch.nativeElement.value = value;
                this.controlText = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    ;
    RxSelectComponent.prototype.ngAfterContentInit = function () {
        var _this = this;
        if (this.formControl)
            this.writeValue(this.formControl.value, true);
        this.checkValid(true);
        if (this.userSource && this.mainSource.length === 0)
            this.setMainSource(this.userSource);
        setTimeout(function () { _this.setValue(); }, 1);
        //if (this.focus && this.selectSearch)
        //  this.renderer.invokeElementMethod(this.selectSearch.nativeElement, "focus", []);
        if (this.maxLength && this.selectSearch)
            this.selectSearch.nativeElement.maxLength = this.maxLength;
    };
    RxSelectComponent.prototype.setValue = function (isBlur, columnName) {
        var _this = this;
        if (isBlur === void 0) { isBlur = false; }
        if (columnName === void 0) { columnName = "key"; }
        if (!this.autoComplete && this.currentValue && this.mainSource.length > 0) {
            var text = this.mainSource.filter(function (t) { return String(t[columnName]).toLowerCase() == String(_this.currentValue).toLowerCase(); })[0];
            if (text) {
                this.writeValue(text.value);
                if (isBlur) {
                    this.updateFormValue(text.key);
                    this.selectSearch.nativeElement.value = text.value;
                }
                return true;
            }
            else {
                this.updateFormValue(undefined);
            }
            return false;
        }
        return true;
    };
    RxSelectComponent.prototype.ngOnChanges = function (source) {
        if (source.params || source.queryParams) {
            this.isObjectChanged = true;
            this.clear();
        }
    };
    RxSelectComponent.prototype.checkValid = function (isValid) {
        var _this = this;
        if (isValid)
            this.validTimeOutId = window.setTimeout(function () {
                for (var i = 0; i < _this.element.classList.length; i++) {
                    _this.isInValid = _this.element.classList[i] == "ng-invalid";
                }
                window.clearTimeout(_this.validTimeOutId);
                _this.validTimeOutId = undefined;
            }, 500);
        else
            this.isInValid = isValid;
    };
    RxSelectComponent.prototype.setMainSource = function (source) {
        var _this = this;
        this.mainSource = this.getTagModelSource(source);
        this.mainSource.forEach(function (t) { return _this.dropSource.push(t); });
        this.clearActiveTabClass();
    };
    RxSelectComponent.prototype.setDropSource = function (source) {
        var _this = this;
        this.dropSource = new Array();
        source.forEach(function (t) { return _this.dropSource.push(t); });
    };
    RxSelectComponent.prototype.getTagModelSource = function (source) {
        var _this = this;
        var textPattern = this.keyValueProps[0].split(/#/g);
        var tags = new Array();
        source.forEach(function (t) {
            var text = '';
            textPattern.forEach(function (x) {
                if (x != "")
                    if (t[x] != undefined)
                        text += t[x];
                    else
                        text += x;
            });
            tags.push(new SelectModel(t[_this.keyValueProps[1]], text, false));
        });
        return tags;
    };
    RxSelectComponent.prototype.resetSource = function (source) {
        this.userSource = source;
        this.mainSource = [];
        this.dropSource = [];
        this.setMainSource(source);
        this.currentValue = "";
        this.selectSearch.nativeElement.value = "";
        this.updateFormValue(undefined);
    };
    RxSelectComponent.prototype.showItems = function (tags, clearExisting) {
    };
    RxSelectComponent.prototype.clear = function (event) {
        if (this.selectSearch && this.selectSearch.nativeElement) {
            this.selectSearch.nativeElement.value = '';
            this.onBlur(event, this.selectSearch.nativeElement.value);
            this.changed.emit({ item: this.selectedTag, text: this.currentValue });
        }
    };
    RxSelectComponent.prototype.registerOnChange = function (fn) {
        this.propagateChange = fn;
    };
    RxSelectComponent.prototype.registerOnTouched = function () { };
    RxSelectComponent.prototype.writeValue = function (value, fromNg) {
        if (fromNg === void 0) { fromNg = false; }
        if (value) {
            this.currentValue = value;
            if (this.selectSearch && this.selectSearch.nativeElement)
                if (this.controlText)
                    this.selectSearch.nativeElement.value = this.controlText;
                else
                    this.selectSearch.nativeElement.value = value;
        }
        else {
            this.currentValue = undefined;
            if (this.selectSearch && this.selectSearch.nativeElement)
                this.selectSearch.nativeElement.value = "";
        }
        if (this.formControl && !fromNg)
            this.formControl.setValue(this.currentValue);
    };
    RxSelectComponent.prototype.caretClick = function (event) {
        var _this = this;
        if (!this.selectDisabled && (this.activeTag == undefined || this.activeTag == "")) {
            var t = setTimeout(function () {
                _this.selectSearch.nativeElement.focus();
                _this.onFocus(event);
            }, 200);
        }
    };
    RxSelectComponent.prototype.onFocus = function (event) {
        var _this = this;
        if ((!this.userSource && this.mainSource.length === 0 && this.lookup) || (this.autoComplete) || this.isObjectChanged) {
            if ((this.currentValue && this.currentValue.length >= this.minimumCharacterSearchLength) || (!this.autoComplete)) {
                var params_1 = [];
                if (this.params)
                    this.params.forEach(function (t) { return params_1.push(t); });
                if (this.autoComplete && this.currentValue) {
                    if (this.valueInQueryParams) {
                        if (!this.queryParams)
                            this.queryParams = {};
                        this.queryParams['q'] = this.currentValue;
                    }
                    else
                        params_1.push(this.currentValue);
                }
                this.isSpinner = true;
                this.get({ path: this.path, params: params_1, queryParams: this.queryParams }).subscribe(function (t) {
                    _this.userSource = t;
                    _this.mainSource = [];
                    _this.dropSource = [];
                    _this.setMainSource(t);
                    _this.showItemBox();
                    _this.isSpinner = false;
                    _this.isObjectChanged = false;
                });
            }
        }
        else if (!this.autoComplete)
            this.showItemBox();
        return false;
    };
    RxSelectComponent.prototype.showItemBox = function () {
        var _this = this;
        this.setActiveTabClass();
        var selectedItem = this.dropSource.filter(function (t) { return t.value == _this.currentValue; })[0];
        if (selectedItem)
            selectedItem.active = true;
    };
    RxSelectComponent.prototype.onBlur = function (event, value) {
        var _this = this;
        if (this.currentFormControl)
            this.currentFormControl.markAsTouched();
        if (this.timeOutId)
            window.clearTimeout(this.timeOutId);
        this.timeOutId = window.setTimeout(function () {
            _this.clearActiveTabClass();
        }, 200);
        this.currentValue = value;
        if (!this.setValue(true, "value") || value == "") {
            if (value != "" && !this.enableFreeText) {
                this.currentValue = "";
                this.selectSearch.nativeElement.value = "";
                this.updateFormValue(undefined);
                this.selectedTag = undefined;
                this.blur.emit({ item: this.selectedTag, text: this.currentValue });
            }
            else {
                this.updateFormValue(value);
                this.blur.emit({ item: undefined, text: value });
            }
        }
    };
    RxSelectComponent.prototype.onKeyup = function (event, scroller) {
        if (event.key == "Tab") {
            this.onFocus(event);
            return;
        }
        var value = event.target.value;
        if (value !== null && event.key !== "ArrowUp" && event.key !== "ArrowDown" && event.key !== "Enter" && event.key !== "ArrowLeft" && event.key !== "ArrowRight") {
            if (this.autoComplete) {
                this.currentValue = value;
                this.onFocus(event);
            }
            else {
                var regex = new RegExp(String(value).toLowerCase());
                this.dropSource = this.mainSource.filter(function (t) { return regex.test(String(t.value).toLowerCase()); });
                this.setActiveTabClass();
            }
            if (this.enableFreeText)
                this.updateFormValue(value);
        }
    };
    RxSelectComponent.prototype.onKeydown = function (event, scroller) {
        if (event.key === "ArrowDown") {
            event.preventDefault();
            if (this.dropSource.length !== this.dropIndex) {
                if (this.dropIndex !== 0) {
                    this.dropSource[this.dropIndex - 1].active = false;
                    this.dropSource[this.dropIndex].active = true;
                    if (this.dropIndex !== this.dropSource.length - 1)
                        this.dropIndex++;
                }
                else {
                    this.dropSource[this.dropIndex].active = true;
                    this.dropIndex++;
                }
            }
            this.changeScroll();
            if (this.openDrop === "")
                this.setActiveTabClass();
        }
        else if (event.key === "ArrowUp") {
            event.preventDefault();
            if ((this.dropSource.length - 1) === this.dropIndex) {
                this.dropSource[this.dropIndex].active = false;
                this.dropIndex--;
                this.dropSource[this.dropIndex].active = true;
            }
            else {
                this.dropSource[this.dropIndex].active = false;
                if (this.dropIndex !== 0)
                    this.dropIndex--;
                this.dropSource[this.dropIndex].active = true;
            }
            this.changeScroll();
            if (this.openDrop === "")
                this.setActiveTabClass();
        }
        else if (event.key === "Enter") {
            event.preventDefault();
            var selectedTag = this.dropSource.filter(function (t) { return t.active; });
            if (selectedTag.length > 0) {
                this.selectedTag = selectedTag[0];
                this.selectSearch.nativeElement.value = selectedTag[0].value;
                this.writeValue(selectedTag[0].value);
                this.clearActiveTabClass();
            }
        }
    };
    RxSelectComponent.prototype.setActiveTabClass = function () {
        this.activeTag = "chosen-container-active";
        this.openDrop = "chosen-with-drop";
    };
    RxSelectComponent.prototype.changeScroll = function () {
        var scrollerElement = document.getElementById(String(this.selectId));
        var childElement = scrollerElement.getElementsByClassName("activeTag")[0];
        if (childElement != undefined)
            scrollerElement.scrollTop = childElement.offsetTop - 50;
    };
    RxSelectComponent.prototype.onChange = function (targetElement) {
        var selectModel = this.dropSource[targetElement.selectedIndex];
        this.selectTag(selectModel);
    };
    RxSelectComponent.prototype.enter = function (targetElement) {
        this.onClick(this.selectedTag, targetElement);
    };
    RxSelectComponent.prototype.onClick = function (tag, tagSearchElement) {
        this.selectTag(tag);
        this.clearValue(tagSearchElement);
        tagSearchElement.value = tag.value;
        this.currentValue = tag.value;
        this.changed.emit({ item: this.selectedTag, text: this.currentValue, sourceItem: this.getSourceItem(tag) });
    };
    RxSelectComponent.prototype.getSourceItem = function (tag) {
        var _this = this;
        var sourceItem = this.userSource.filter(function (t) { return t[_this.keyValueProps[1]] == tag.key; })[0];
        return sourceItem;
    };
    RxSelectComponent.prototype.selectTag = function (tag) {
        tag.active = false;
        this.selectedTag = tag;
        this.clearActiveTabClass();
        this.updateFormValue(this.selectedTag.key);
    };
    RxSelectComponent.prototype.updateFormValue = function (value) {
        this.propagateChange(value);
        if (this.formControl)
            this.formControl.patchValue(value);
    };
    RxSelectComponent.prototype.onMouseover = function (tag, i) {
        this.dropSource.forEach(function (t) { return t.active = false; });
        if (tag && (i != undefined)) {
            this.dropIndex = i;
            this.selectActive = false;
            tag.active = true;
        }
        else
            this.selectActive = true;
    };
    RxSelectComponent.prototype.clearValue = function (element) {
        element.value = "";
        //this.renderer.invokeElementMethod(element, "focus", []);
    };
    RxSelectComponent.prototype.clearActiveTabClass = function () {
        this.activeTag = "";
        this.openDrop = "";
        this.dropSource.forEach(function (tag) { return tag.active = false; });
    };
    RxSelectComponent.prototype.subscribeFormControl = function () {
        var _this = this;
        this.currentFormControl.statusChanges.subscribe(function (t) {
            _this.isInValid = t === "INVALID";
        });
    };
    RxSelectComponent.prototype.validate = function (formControl) {
        if (!this.currentFormControl) {
            this.currentFormControl = formControl;
            this.subscribeFormControl();
        }
        return null;
    };
    RxSelectComponent.prototype.ngOnDestroy = function () {
        var tString = '';
        this.mainSource = [];
    };
    var RxSelectComponent_1;
    RxSelectComponent.ctorParameters = function () { return [
        { type: ElementRef },
        { type: Renderer2 }
    ]; };
    __decorate([
        ViewChild("selectSearch", { static: false })
    ], RxSelectComponent.prototype, "selectSearch", void 0);
    __decorate([
        Output()
    ], RxSelectComponent.prototype, "blur", void 0);
    __decorate([
        Output()
    ], RxSelectComponent.prototype, "changed", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "mainClass", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "maxLength", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "selectPlaceholder", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "showSelectItem", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "controlTabIndex", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "source", null);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "valueInQueryParams", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "selectDisabled", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "keyValueProps", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "focus", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "path", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "params", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "queryParams", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "autoComplete", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "minimumCharacterSearchLength", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "enableFreeText", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "formControl", void 0);
    __decorate([
        Input()
    ], RxSelectComponent.prototype, "text", null);
    RxSelectComponent = RxSelectComponent_1 = __decorate([
        Component({
            selector: 'rx-select',
            template: "\n<div class=\"chosen-container {{openDrop}} {{activeTag}} \" [class.rxMessage-control-element]=\"!isInValid\" title=\"\">\n    <ul class=\"chosen-choices\">\n        <li class=\"search-field\">\n            <span class=\"input-group\">\n                <input [class]=\"mainClass\" [tabindex]=\"controlTabIndex\" type=\"text\" [placeholder]=\"selectPlaceholder\" [disabled]=\"selectDisabled\" #selectSearch (click)=\"onFocus($event)\" (blur)=\"onBlur($event,$event.target.value)\" (keydown)=\"onKeydown($event,scroller)\" (keydown.enter)=\"enter($event.target)\" (keyup)=\"onKeyup($event,scroller)\" class=\"form-control\" autocomplete=\"off\">\n                <span class=\"input-group-append\">\n                  <span class=\"input-group-text\">\n                    <i class=\"fa fa-spinner fa-pulse\" [class.d-none]=\"!isSpinner\"></i>\n                    <i class=\"fa fa-caret-down\"  (click)=\"caretClick($event)\" [class.d-none]=\"!(!isSpinner && !autoComplete)\"></i>\n                  </span>\n                </span>\n            </span>\n        </li>\n    </ul>\n    <div class=\"chosen-drop\"  #scroller>\n        <ul class=\"chosen-results\" [id]=\"selectId\">\n          <li class=\"active-result\" *ngIf=\"selectPlaceholder\" (mouseover)=\"onMouseover()\" (click)=\"clear($event)\" [class.highlighted]=\"selectActive\">{{selectPlaceholder}}</li>\n            <li class=\"active-result\" *ngFor=\"let tag of dropSource;let i = index\"  (click)=\"onClick(tag,selectSearch)\" (mouseover)=\"onMouseover(tag,i)\" [class.highlighted]=\"tag.active\" [class.activeTag]=\"tag.active\">{{tag.value}}</li>\n        </ul>\n    </div>\n</div>\n",
            providers: [
                { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(function () { return RxSelectComponent_1; }), multi: true },
                { provide: NG_VALIDATORS, useExisting: forwardRef(function () { return RxSelectComponent_1; }), multi: true }
            ],
            exportAs: 'select'
        })
    ], RxSelectComponent);
    return RxSelectComponent;
}(RxHttp));
var RxSelectModule = /** @class */ (function () {
    function RxSelectModule() {
    }
    RxSelectModule = __decorate([
        NgModule({
            imports: [CommonModule, FormsModule, ReactiveFormsModule],
            exports: [RxSelectComponent],
            declarations: [RxSelectComponent]
        })
    ], RxSelectModule);
    return RxSelectModule;
}());

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

export { RxSelectComponent, RxSelectModule, SelectModel };
//# sourceMappingURL=rxweb-angular-select.js.map
