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';

var TagModel = /** @class */ (function () {
    function TagModel(id, text, active, isRecordInvactive) {
        if (isRecordInvactive === void 0) { isRecordInvactive = false; }
        this.id = id;
        this.text = text;
        this.active = active;
        this.isRecordInvactive = isRecordInvactive;
    }
    return TagModel;
}());

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 RxTagComponent = /** @class */ (function () {
    function RxTagComponent(elementRef, renderer) {
        this.elementRef = elementRef;
        this.renderer = renderer;
        this.propagateChange = function () { };
        this.dropIndex = 0;
        this.inputDisabled = false;
        this.isLimitExceeded = false;
        this.isInValid = false;
        this.isCalledFromWriteValue = false;
        this.isSpinner = false;
        this.isServerCalled = false;
        this.removed = new EventEmitter();
        this.added = new EventEmitter();
        this.focus = false;
        this.mainSource = new Array();
        this.selectedTags = new Array();
        this.dropSource = new Array();
        this.inActiveSource = new Array();
        this.maxSelectionMessage = MultiLingualData.get("global.control.rx-tag.message-max-selection");
        this.splitCharacter = MultiLingualData.get("global.control.rx-tag.split-character");
        this.placeholder = this.placeholder || MultiLingualData.get("global.control.rx-tag.placeholder");
        this.placeholder = this.placeholder || "";
        if (!this.splitCharacter)
            this.splitCharacter = ",";
        this.element = elementRef.nativeElement;
    }
    RxTagComponent_1 = RxTagComponent;
    Object.defineProperty(RxTagComponent.prototype, "source", {
        set: function (value) {
            if (value) {
                this.userSource = value;
                if (this.keyValueProps)
                    this.setMainSource(this.userSource);
            }
        },
        enumerable: true,
        configurable: true
    });
    RxTagComponent.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);
            if (this.currentValue)
                this.setSelectedTags(this.mainSource, this.currentValue);
        }
        else if (this.itemTexts && this.currentValue) {
            var selectedItemSource = [];
            var splitIds = this.currentValue.split(this.splitCharacter);
            this.itemTexts.split(this.splitCharacter).forEach(function (t, i) {
                var jObject = {};
                jObject[_this.keyValueProps[1]] = splitIds[i];
                var textPattern = _this.keyValueProps[0].split(/#/g);
                jObject[textPattern[0]] = t;
                selectedItemSource.push(jObject);
            });
            var itemSource = this.getTagModelSource(selectedItemSource);
            if (this.currentValue)
                this.setSelectedTags(itemSource, this.currentValue);
        }
    };
    RxTagComponent.prototype.ngOnChanges = function (source) {
        var _this = this;
        if (this.focus)
            var t = setTimeout(function () {
                _this.applyFocus(_this.viewChild.nativeElement);
            }, 1000);
    };
    RxTagComponent.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";
                    if (_this.isInValid)
                        break;
                }
                window.clearTimeout(_this.validTimeOutId);
                _this.validTimeOutId = undefined;
            }, 500);
        else
            this.isInValid = isValid;
    };
    RxTagComponent.prototype.setMainSource = function (source) {
        var _this = this;
        this.inActiveSource = new Array();
        this.mainSource = this.getTagModelSource(source);
        this.mainSource.forEach(function (t) {
            return _this.dropSource.push(t);
        });
    };
    RxTagComponent.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;
            });
            if ((t["status"] == undefined) || (t["status"] != undefined && t["status"] == true))
                tags.push(new TagModel(t[_this.keyValueProps[1]], text, false));
            else
                _this.inActiveSource.push(new TagModel(t[_this.keyValueProps[1]], text, false, true));
        });
        return tags;
    };
    RxTagComponent.prototype.setSelectedTags = function (source, tags) {
        var _this = this;
        this.selectedTags = new Array();
        tags.toString().split(this.splitCharacter).forEach(function (v) {
            if (v != "") {
                var baseId = v;
                var result = source.filter(function (t) { return t.id == baseId; });
                if (result.length > 0 && _this.selectedTags.filter(function (t) { return t.id == baseId; }).length === 0)
                    _this.selectTag(result[0]);
                else {
                    result = _this.inActiveSource.filter(function (t) { return t.id == baseId; });
                    if (result.length > 0 && _this.selectedTags.filter(function (t) { return t.id == baseId; }).length === 0)
                        _this.selectTag(result[0]);
                }
            }
        });
    };
    RxTagComponent.prototype.setDropSource = function (source) {
        var _this = this;
        this.dropSource = new Array();
        source.forEach(function (t) { return _this.dropSource.push(t); });
    };
    RxTagComponent.prototype.applyFocus = function (tagSearch) {
        tagSearch.focus();
        this.focus = false;
    };
    RxTagComponent.prototype.reset = function () {
        this.setDropSource(this.mainSource);
        this.setSelectedTags(this.mainSource, "");
        this.propagateChange(undefined);
    };
    RxTagComponent.prototype.changeTagSource = function (source) {
        this.inActiveSource = new Array();
        var tagModels = this.getTagModelSource(source);
        this.setDropSource(tagModels);
        this.setSelectedTags(tagModels, this.getTagString());
    };
    RxTagComponent.prototype.showTag = function (tags, clearExisting) {
        var _this = this;
        if (tags && !this.limitExceded()) {
            if (clearExisting && tags.split(this.splitCharacter).length > parseInt(this.maxSelection)) {
                return;
            }
            this.selectedTags.forEach(function (tag) { return _this.dropSource.push(tag); });
            tags = clearExisting ? tags : this.getTagString() + this.splitCharacter + tags;
            this.setSelectedTags(this.dropSource, tags);
        }
    };
    RxTagComponent.prototype.clear = function () {
        var _this = this;
        this.isCalledFromWriteValue = false;
        this.selectedTags.forEach(function (t) { return _this.dropSource.push(t); });
        this.selectedTags = new Array();
        this.updateFormValue();
    };
    RxTagComponent.prototype.selectAll = function () {
        var _this = this;
        var dropTags = new Array();
        this.dropSource.forEach(function (t) { return dropTags.push(t); });
        dropTags.forEach(function (t) { return _this.selectTag(t); });
    };
    RxTagComponent.prototype.getTagString = function () {
        var _this = this;
        var tagString = '';
        var selectCount = 0;
        this.selectedTags.forEach(function (t) {
            if ((selectCount === _this.selectedTags.length - 1)) {
                if (t.id == -1)
                    tagString += t.text;
                else
                    tagString += t.id;
            }
            else {
                if (t.id == -1)
                    tagString += t.text + _this.splitCharacter;
                else
                    tagString += t.id + _this.splitCharacter;
            }
            selectCount++;
        });
        return tagString;
    };
    RxTagComponent.prototype.registerOnChange = function (fn) {
        this.propagateChange = fn;
    };
    RxTagComponent.prototype.registerOnTouched = function () { };
    RxTagComponent.prototype.writeValue = function (value, fromNg) {
        if (fromNg === void 0) { fromNg = false; }
        if (value)
            this.currentValue = value;
        if (this.selectedTags.length > 0) {
            this.isCalledFromWriteValue = true;
            this.ngAfterContentInit();
        }
        if (this.formControl && !fromNg)
            this.formControl.setValue(this.currentValue);
    };
    RxTagComponent.prototype.removeTag = function (tag) {
        if (!this.tagDisabled) {
            this.removed.emit(tag);
            var indexOf = this.selectedTags.indexOf(tag);
            this.selectedTags.splice(indexOf, 1);
            if (!tag.isRecordInvactive && tag.id != -1)
                if (this.isServerCalled || !this.lookup)
                    this.dropSource.push(tag);
            this.updateFormValue();
        }
    };
    RxTagComponent.prototype.onFocus = function (event) {
        this.setActiveTabClass();
    };
    RxTagComponent.prototype.onBlur = function (event) {
        var _this = this;
        if (this.timeOutId)
            window.clearTimeout(this.timeOutId);
        this.timeOutId = window.setTimeout(function () {
            if (_this.freeTextEnabled) {
                _this.enter(event.target);
            }
            _this.clearActiveTabClass();
        }, 200);
    };
    RxTagComponent.prototype.onKeyup = function (event, scroller) {
        var _this = this;
        var value = event.srcElement.value;
        var regex = new RegExp(value.toLocaleLowerCase());
        if (value !== null && event.keyCode !== 40 && event.keyCode !== 13 && event.keyCode !== 37) {
            this.dropSource = this.mainSource.filter(function (t) { return regex.test(t.text.toLowerCase()); });
            this.selectedTags.forEach(function (t) {
                if (_this.dropSource.length > 0) {
                    var indexOf = _this.dropSource.indexOf(t);
                    if (indexOf != -1)
                        _this.dropSource.splice(indexOf, 1);
                }
            });
            this.setActiveTabClass();
        }
    };
    RxTagComponent.prototype.onKeydown = function (event, scroller) {
        if (event.keyCode === 40) {
            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;
                (this.dropIndex !== this.dropSource.length - 1) ? this.dropIndex++ : 0;
                this.changeScroll(scroller);
                if (this.openDrop === "")
                    this.setActiveTabClass();
            }
        }
        else if (event.keyCode === 38) {
            event.preventDefault();
            this.dropSource[this.dropIndex].active = false;
            if (this.dropIndex !== 0)
                this.dropIndex--;
            this.dropSource[this.dropIndex].active = true;
            (this.dropIndex == 0) ? this.dropIndex++ : 0;
        }
        else if (event.keyCode === 13) {
            event.preventDefault();
            var selectedTag = this.dropSource.filter(function (t) { return t.active; });
            if (selectedTag.length > 0) {
                this.selectTag(selectedTag[0]);
                this.clearValue(event.srcElement);
            }
        }
    };
    RxTagComponent.prototype.limitExceded = function () {
        this.isLimitExceeded = !(parseInt(this.maxSelection) !== this.selectedTags.length);
        return this.isLimitExceeded;
    };
    RxTagComponent.prototype.setActiveTabClass = function () {
        if (this.limitExceded())
            this.maxSelectionMessage = this.maxSelectionMessage.replace('#maxSelection#', this.maxSelection);
        this.activeTag = "chosen-container-active";
        this.openDrop = "chosen-with-drop";
    };
    RxTagComponent.prototype.changeScroll = function (scroller) {
        if (this.dropIndex > 8) {
            scroller.scrollTop = scroller.scrollTop - 50;
        }
    };
    RxTagComponent.prototype.enter = function (targetElement) {
        if (this.freeTextEnabled) {
            var value = targetElement.value;
            if (value) {
                var tagModel = new TagModel(-1, value, true);
                var result = this.selectedTags.filter(function (t) { return t.text.toLowerCase() == value.toLowerCase(); })[0];
                if (!result) {
                    this.selectedTags.push(tagModel);
                    this.updateFormValue();
                }
                this.clearValue(targetElement);
            }
        }
    };
    RxTagComponent.prototype.onClick = function (tag, tagSearchElement) {
        this.selectTag(tag);
        this.clearValue(tagSearchElement);
    };
    RxTagComponent.prototype.selectTag = function (tag) {
        this.added.emit(tag);
        tag.active = false;
        var indexOf = this.dropSource.indexOf(tag);
        this.dropSource.splice(indexOf, 1);
        this.selectedTags.push(tag);
        this.clearActiveTabClass();
        if (!this.isCalledFromWriteValue)
            this.updateFormValue();
        this.isCalledFromWriteValue = false;
    };
    RxTagComponent.prototype.updateFormValue = function () {
        var _this = this;
        var value = "";
        var count = 0;
        this.selectedTags.forEach(function (t) {
            if (count === 0) {
                if (t.id == -1)
                    value += t.text;
                else
                    value += t.id;
            }
            else {
                if (t.id == -1)
                    value += _this.splitCharacter + t.text;
                else
                    value += _this.splitCharacter + t.id;
            }
            count++;
        });
        if (!this.isServerCalled)
            this.currentValue = value;
        this.propagateChange(this.selectedTags.length == 0 ? undefined : value);
        if (this.formControl)
            this.formControl.patchValue(value);
    };
    RxTagComponent.prototype.onMouseover = function (tag) {
        this.dropSource.forEach(function (t) { return t.active = false; });
        tag.active = true;
    };
    RxTagComponent.prototype.clearValue = function (element) {
        element.value = "";
        //this.renderer.invokeElementMethod(element, "focus", []);
    };
    RxTagComponent.prototype.clearActiveTabClass = function () {
        this.activeTag = "";
        this.openDrop = "";
        this.dropIndex = 0;
        this.dropSource.forEach(function (tag) { return tag.active = false; });
    };
    RxTagComponent.prototype.subscribeFormControl = function () {
        var _this = this;
        this.currentFormControl.statusChanges.subscribe(function (t) {
            _this.isInValid = t === "INVALID";
        });
    };
    RxTagComponent.prototype.validate = function (formControl) {
        if (!this.currentFormControl) {
            this.currentFormControl = formControl;
            this.subscribeFormControl();
        }
        return null;
    };
    RxTagComponent.prototype.ngOnDestroy = function () {
        var tString = '';
        this.selectedTags.forEach(function (t) { return tString += t.id; });
        this.selectedTags = [];
        this.mainSource = [];
    };
    var RxTagComponent_1;
    RxTagComponent.ctorParameters = function () { return [
        { type: ElementRef },
        { type: Renderer2 }
    ]; };
    __decorate([
        ViewChild('tagSearch', { static: false })
    ], RxTagComponent.prototype, "viewChild", void 0);
    __decorate([
        Output()
    ], RxTagComponent.prototype, "removed", void 0);
    __decorate([
        Output()
    ], RxTagComponent.prototype, "added", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "mainClass", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "freeTextEnabled", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "lookup", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "controlTabIndex", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "formControl", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "params", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "queryParams", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "placeholder", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "source", null);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "tagDisabled", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "maxSelection", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "keyValueProps", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "focus", void 0);
    __decorate([
        Input()
    ], RxTagComponent.prototype, "itemTexts", void 0);
    RxTagComponent = RxTagComponent_1 = __decorate([
        Component({
            selector: 'rx-tag',
            template: "<div class=\"chosen-container chosen-container-multi  {{openDrop}} {{activeTag}} \" [class.rxMessage-control-element]=\"!isInValid\" style=\"width: 100%;\" title=\"\">\r\n    <ul class=\"chosen-choices form-control rounded-0\">\r\n        <li class=\"search-choice\" *ngFor=\"let tag of selectedTags\">\r\n            <span>{{tag.text}}</span>\r\n            <i class=\"close \" *ngIf=\"!tagDisabled\" (click)=\"removeTag(tag)\">&times;</i>\r\n        </li>\r\n        <li class=\"search-field\">\r\n            <input [tabindex]=\"controlTabIndex\" [class]=\"mainClass\" [placeholder]=\"selectedTags.length == 0 ? placeholder : ''\" type=\"text\" #tagSearch [disabled]=\"tagDisabled\" (click)=\"onFocus($event)\" (focus)=\"onFocus($event)\" (blur)=\"onBlur($event)\" (keydown)=\"onKeydown($event,scroller)\" (keydown.enter)=\"enter($event.target)\" (keyup)=\"onKeyup($event,scroller)\" value=\"\" class=\"\" autocomplete=\"off\">\r\n        </li>\r\n    </ul>\r\n    <div class=\"chosen-drop\" #scroller>\r\n        <ul class=\"chosen-results\" *ngIf=\"!isLimitExceeded\">\r\n            <li class=\"active-result\" *ngFor=\"let tag of dropSource \" (click)=\"onClick(tag,tagSearch)\" (mouseover)=\"onMouseover(tag)\" [class.highlighted]=\"tag.active\">{{tag.text}}</li>\r\n        </ul>\r\n        <ul class=\"chosen-results\" *ngIf=\"isLimitExceeded\">\r\n            <li class=\"active-result\">{{maxSelectionMessage}}</li>\r\n        </ul>\r\n    </div>\r\n</div>",
            providers: [
                { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(function () { return RxTagComponent_1; }), multi: true },
                { provide: NG_VALIDATORS, useExisting: forwardRef(function () { return RxTagComponent_1; }), multi: true }
            ],
            exportAs: 'tag'
        })
    ], RxTagComponent);
    return RxTagComponent;
}());
var RxTagModule = /** @class */ (function () {
    function RxTagModule() {
    }
    RxTagModule = __decorate([
        NgModule({
            imports: [CommonModule, FormsModule, ReactiveFormsModule],
            exports: [RxTagComponent],
            declarations: [RxTagComponent]
        })
    ], RxTagModule);
    return RxTagModule;
}());

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

export { RxTagComponent, RxTagModule };
//# sourceMappingURL=rxweb-angular-tag.js.map
