import { ENTER, COMMA } from '@angular/cdk/keycodes';
import * as i0 from '@angular/core';
import { Directive, Input, HostListener, Component, ChangeDetectionStrategy, ViewChild, NgModule } from '@angular/core';
import * as i2 from '@angular/forms';
import { Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import * as i5 from '@angular/material/autocomplete';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { equals, HelperPipesModule } from '@aztrix/helpers';
import { FormControl } from '@ngneat/reactive-forms';
import { BehaviorSubject, Subscription, combineLatest } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i3 from '@angular/material/form-field';
import { MatFormFieldModule } from '@angular/material/form-field';
import * as i4 from '@angular/material/core';
import * as i6 from '@aztrix/icons';
import { IconsModule } from '@aztrix/icons';
import * as i7 from '@angular/material/chips';
import { MatChipsModule } from '@angular/material/chips';
import * as i8 from '@aztrix/components/button';
import { ButtonModule } from '@aztrix/components/button';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';

class DisableSpecialFileCharactersDirective {
    set axDisableSpecialFileCharacters(disableSpecialFileCharacters) {
        this._disableSpecialFileCharacters = disableSpecialFileCharacters;
    }
    constructor(el) {
        this.el = el;
        this.regex = /[\\/:*?"<>|]/g;
        this._disableSpecialFileCharacters = true;
    }
    onKeyPress(event) {
        this.validateFields(event);
        return this._disableSpecialFileCharacters ? !this.regex.test(event.key) : true;
    }
    onPaste(event) {
        this.validateFields(event);
    }
    validateFields(event) {
        if (this._disableSpecialFileCharacters) {
            setTimeout(() => {
                this.el.nativeElement.value = this.el.nativeElement.value.replace(this.regex, '');
                event.preventDefault();
            }, 100);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: DisableSpecialFileCharactersDirective, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "17.3.12", type: DisableSpecialFileCharactersDirective, selector: "[axDisableSpecialFileCharacters]", inputs: { axDisableSpecialFileCharacters: "axDisableSpecialFileCharacters" }, host: { listeners: { "keypress": "onKeyPress($event)", "paste": "onPaste($event)" } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: DisableSpecialFileCharactersDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[axDisableSpecialFileCharacters]',
                }]
        }], ctorParameters: () => [{ type: i0.ElementRef }], propDecorators: { axDisableSpecialFileCharacters: [{
                type: Input
            }], onKeyPress: [{
                type: HostListener,
                args: ['keypress', ['$event']]
            }], onPaste: [{
                type: HostListener,
                args: ['paste', ['$event']]
            }] } });

class ChipsEditComponent {
    constructor(_changeDetector) {
        this._changeDetector = _changeDetector;
        this.required = false;
        this.disableSpecialFileCharacters = false;
        this.readonly = false;
        this.subscriptSizing = 'dynamic';
        this.separatorKeysCodes = [ENTER, COMMA];
        this.chipsCtrl = new FormControl();
        this.chips = [];
        this.chips$ = new BehaviorSubject([]);
        this._subscriptions = new Subscription();
        this._formSubscription = new Subscription();
        this.filteredChips$ = combineLatest([
            this.chipsCtrl.valueChanges.pipe(startWith(this.chipsCtrl.value)),
            this.chips$,
        ]).pipe(map(([value]) => this.autocompleteValues?.filter((chip) => (!value || chip.toLowerCase().indexOf(value?.toLowerCase()) === 0) &&
            !this._duplicate(chip))));
    }
    ngOnInit() {
        this._subscriptions.add(this.form.touch$.subscribe((touched) => {
            if (touched) {
                this.chipsCtrl.markAsTouched();
            }
            else {
                this.chipsCtrl.markAsUntouched();
            }
            this._changeDetector.markForCheck();
        }));
        this._subscriptions.add(this.chipsCtrl.touch$.subscribe((touched) => {
            if (touched) {
                this.form.markAllAsTouched();
            }
            else {
                this.form.markAllAsTouched();
            }
        }));
    }
    ngOnChanges(changes) {
        if (changes.required) {
            if (this.required) {
                this.chipsCtrl.setValidators(Validators.required);
            }
            else {
                this.chipsCtrl.setValidators([]);
            }
        }
        if (changes.form && this.form) {
            this._formSubscription.unsubscribe();
            this._formSubscription = this.form.valueChanges
                .pipe(startWith(this.form.value))
                .subscribe((property) => {
                const values = property?.value?.split(',').filter((v) => v?.length);
                if (!equals(this.chips$.value, values) && values) {
                    this.chips = values;
                    this.chips$.next(values);
                }
            });
            this._formSubscription.add(this.form.statusChanges.subscribe(() => {
                this._setFormState();
            }));
        }
    }
    ngOnDestroy() {
        if (!this._formSubscription.closed) {
            this._formSubscription.unsubscribe();
        }
        if (!this._subscriptions.closed) {
            this._subscriptions.unsubscribe();
        }
    }
    add({ chipInput, value }) {
        value = (value || '').trim();
        if (value && !this._duplicate(value)) {
            this.chips.push(value);
            this.chips$.next(this.chips);
        }
        if (chipInput) {
            chipInput.inputElement.value = '';
        }
        this.chipsCtrl.setValue(null);
        this._setFormValue();
    }
    remove(value) {
        const index = this.chips.indexOf(value);
        if (index >= 0) {
            this.chips.splice(index, 1);
            this.chips$.next(this.chips);
        }
        this._setFormState();
        this._setFormValue();
    }
    selected(event) {
        if (!this._duplicate(event.option.viewValue)) {
            this.chips.push(event.option.viewValue.trim());
            this.chips$.next(this.chips);
        }
        this.chipsCtrl.setValue(null);
        this._setFormState();
        this._setFormValue();
    }
    clearValue() {
        this.chips = [];
        this.chips$.next(this.chips);
        this.form.reset();
        this.form.markAsDirty();
    }
    _setFormValue() {
        const value = this.chips$.value?.join(',');
        this.form.setValue({ ...this.form.value, value });
        this.form.markAsDirty();
    }
    _setFormState() {
        this.chipList.errorState = this.form.invalid;
        this.chipsCtrl.updateValueAndValidity();
    }
    _duplicate(valueToCheck) {
        return (this.chips
            .map((chip) => chip.toLowerCase())
            .findIndex((chip) => valueToCheck.trim().toLowerCase() === chip) >= 0);
    }
    get hasValue() {
        return this.form?.value?.value;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ChipsEditComponent, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "17.3.12", type: ChipsEditComponent, selector: "ax-chips-edit", inputs: { form: "form", label: "label", hint: "hint", required: "required", autocompleteValues: "autocompleteValues", disableSpecialFileCharacters: "disableSpecialFileCharacters", errorsTemplate: "errorsTemplate", readonly: "readonly", subscriptSizing: "subscriptSizing" }, viewQueries: [{ propertyName: "chipList", first: true, predicate: ["chipList"], descendants: true }, { propertyName: "matAutocomplete", first: true, predicate: ["auto"], descendants: true }], usesOnChanges: true, ngImport: i0, template: "<div>\n  <mat-form-field\n    class=\"c-input\"\n    [ngClass]=\"{'remove-subtext': !errorsTemplate && !hint, readonly: readonly}\"\n    appearance=\"outline\"\n    style=\"width: 100%\"\n    [subscriptSizing]=\"subscriptSizing\"\n  >\n    <mat-label>{{ label }}</mat-label>\n    <mat-chip-grid\n      [formControl]=\"chipsCtrl\"\n      [disabled]=\"form.disabled\"\n      #chipGrid\n      aria-label=\"Chips selection\"\n    >\n      <mat-chip-row\n        *ngFor=\"let chip of chips$ | async\"\n        [editable]=\"false\"\n        [removable]=\"true\"\n        (removed)=\"remove(chip)\"\n      >\n        {{ chip }}\n        <ax-icon matChipRemove class=\"icon\" name=\"close\"></ax-icon>\n      </mat-chip-row>\n    </mat-chip-grid>\n    <input\n      matChipInputAddOnBlur\n      [axDisableSpecialFileCharacters]=\"disableSpecialFileCharacters\"\n      [matAutocomplete]=\"auto\"\n      [matChipInputFor]=\"chipGrid\"\n      [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\"\n      [readonly]=\"readonly\"\n      (matChipInputTokenEnd)=\"add($event)\"\n    />\n    <mat-hint class=\"hint\" align=\"end\">\n      {{ hint }}\n    </mat-hint>\n    <mat-error *ngIf=\"errorsTemplate\">\n      <ng-template [ngTemplateOutlet]=\"errorsTemplate\"></ng-template>\n    </mat-error>\n    <mat-autocomplete #auto=\"matAutocomplete\" (optionSelected)=\"selected($event)\">\n      @for (chip of filteredChips$ | async; track chip) {\n        <mat-option [value]=\"chip\">{{ chip }}</mat-option>\n      }\n    </mat-autocomplete>\n\n    <button\n      axButton\n      icon-button\n      type=\"button\"\n      *ngIf=\"form?.enabled && hasValue && !readonly\"\n      matSuffix\n      (click)=\"clearValue()\"\n    >\n      <ax-icon class=\"icon\" name=\"close\"></ax-icon>\n    </button>\n  </mat-form-field>\n</div>\n", styles: [":host{display:block;position:relative}:host .remove-subtext{margin-bottom:4px}:host .remove-subtext .mat-mdc-form-field-subscript-wrapper{display:none}\n"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "component", type: i3.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3.MatLabel, selector: "mat-label" }, { kind: "directive", type: i3.MatHint, selector: "mat-hint", inputs: ["align", "id"] }, { kind: "directive", type: i3.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "directive", type: i3.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "component", type: i4.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "component", type: i5.MatAutocomplete, selector: "mat-autocomplete", inputs: ["aria-label", "aria-labelledby", "displayWith", "autoActiveFirstOption", "autoSelectActiveOption", "requireSelection", "panelWidth", "disableRipple", "class", "hideSingleSelectionIndicator"], outputs: ["optionSelected", "opened", "closed", "optionActivated"], exportAs: ["matAutocomplete"] }, { kind: "directive", type: i5.MatAutocompleteTrigger, selector: "input[matAutocomplete], textarea[matAutocomplete]", inputs: ["matAutocomplete", "matAutocompletePosition", "matAutocompleteConnectedTo", "autocomplete", "matAutocompleteDisabled"], exportAs: ["matAutocompleteTrigger"] }, { kind: "component", type: i6.IconComponent, selector: "ax-icon", inputs: ["name", "inline"] }, { kind: "component", type: i7.MatChipGrid, selector: "mat-chip-grid", inputs: ["disabled", "placeholder", "required", "value", "errorStateMatcher"], outputs: ["change", "valueChange"] }, { kind: "directive", type: i7.MatChipInput, selector: "input[matChipInputFor]", inputs: ["matChipInputFor", "matChipInputAddOnBlur", "matChipInputSeparatorKeyCodes", "placeholder", "id", "disabled"], outputs: ["matChipInputTokenEnd"], exportAs: ["matChipInput", "matChipInputFor"] }, { kind: "directive", type: i7.MatChipRemove, selector: "[matChipRemove]" }, { kind: "component", type: i7.MatChipRow, selector: "mat-chip-row, [mat-chip-row], mat-basic-chip-row, [mat-basic-chip-row]", inputs: ["editable"], outputs: ["edited"] }, { kind: "directive", type: i8.ButtonDirective, selector: "[axButton]", inputs: ["color", "labelHideMobile", "smallButton", "bigButton", "fullWidth", "filled", "outline", "icon-button", "hoverLabel", "hover", "lowercase", "disabled"] }, { kind: "directive", type: DisableSpecialFileCharactersDirective, selector: "[axDisableSpecialFileCharacters]", inputs: ["axDisableSpecialFileCharacters"] }, { kind: "pipe", type: i1.AsyncPipe, name: "async" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ChipsEditComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-chips-edit', changeDetection: ChangeDetectionStrategy.OnPush, template: "<div>\n  <mat-form-field\n    class=\"c-input\"\n    [ngClass]=\"{'remove-subtext': !errorsTemplate && !hint, readonly: readonly}\"\n    appearance=\"outline\"\n    style=\"width: 100%\"\n    [subscriptSizing]=\"subscriptSizing\"\n  >\n    <mat-label>{{ label }}</mat-label>\n    <mat-chip-grid\n      [formControl]=\"chipsCtrl\"\n      [disabled]=\"form.disabled\"\n      #chipGrid\n      aria-label=\"Chips selection\"\n    >\n      <mat-chip-row\n        *ngFor=\"let chip of chips$ | async\"\n        [editable]=\"false\"\n        [removable]=\"true\"\n        (removed)=\"remove(chip)\"\n      >\n        {{ chip }}\n        <ax-icon matChipRemove class=\"icon\" name=\"close\"></ax-icon>\n      </mat-chip-row>\n    </mat-chip-grid>\n    <input\n      matChipInputAddOnBlur\n      [axDisableSpecialFileCharacters]=\"disableSpecialFileCharacters\"\n      [matAutocomplete]=\"auto\"\n      [matChipInputFor]=\"chipGrid\"\n      [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\"\n      [readonly]=\"readonly\"\n      (matChipInputTokenEnd)=\"add($event)\"\n    />\n    <mat-hint class=\"hint\" align=\"end\">\n      {{ hint }}\n    </mat-hint>\n    <mat-error *ngIf=\"errorsTemplate\">\n      <ng-template [ngTemplateOutlet]=\"errorsTemplate\"></ng-template>\n    </mat-error>\n    <mat-autocomplete #auto=\"matAutocomplete\" (optionSelected)=\"selected($event)\">\n      @for (chip of filteredChips$ | async; track chip) {\n        <mat-option [value]=\"chip\">{{ chip }}</mat-option>\n      }\n    </mat-autocomplete>\n\n    <button\n      axButton\n      icon-button\n      type=\"button\"\n      *ngIf=\"form?.enabled && hasValue && !readonly\"\n      matSuffix\n      (click)=\"clearValue()\"\n    >\n      <ax-icon class=\"icon\" name=\"close\"></ax-icon>\n    </button>\n  </mat-form-field>\n</div>\n", styles: [":host{display:block;position:relative}:host .remove-subtext{margin-bottom:4px}:host .remove-subtext .mat-mdc-form-field-subscript-wrapper{display:none}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }], propDecorators: { form: [{
                type: Input
            }], label: [{
                type: Input
            }], hint: [{
                type: Input
            }], required: [{
                type: Input
            }], autocompleteValues: [{
                type: Input
            }], disableSpecialFileCharacters: [{
                type: Input
            }], errorsTemplate: [{
                type: Input
            }], readonly: [{
                type: Input
            }], subscriptSizing: [{
                type: Input
            }], chipList: [{
                type: ViewChild,
                args: ['chipList']
            }], matAutocomplete: [{
                type: ViewChild,
                args: ['auto']
            }] } });

class ChipsEditModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ChipsEditModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: ChipsEditModule, declarations: [ChipsEditComponent, DisableSpecialFileCharactersDirective], imports: [CommonModule,
            FormsModule,
            ReactiveFormsModule,
            MatFormFieldModule,
            MatInputModule,
            MatSelectModule,
            MatAutocompleteModule,
            ScrollingModule,
            IconsModule,
            HelperPipesModule,
            MatChipsModule,
            ButtonModule], exports: [ChipsEditComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ChipsEditModule, imports: [CommonModule,
            FormsModule,
            ReactiveFormsModule,
            MatFormFieldModule,
            MatInputModule,
            MatSelectModule,
            MatAutocompleteModule,
            ScrollingModule,
            IconsModule,
            HelperPipesModule,
            MatChipsModule,
            ButtonModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ChipsEditModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [ChipsEditComponent, DisableSpecialFileCharactersDirective],
                    imports: [
                        CommonModule,
                        FormsModule,
                        ReactiveFormsModule,
                        MatFormFieldModule,
                        MatInputModule,
                        MatSelectModule,
                        MatAutocompleteModule,
                        ScrollingModule,
                        IconsModule,
                        HelperPipesModule,
                        MatChipsModule,
                        ButtonModule,
                    ],
                    exports: [ChipsEditComponent],
                }]
        }] });

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

export { ChipsEditComponent, ChipsEditModule };
//# sourceMappingURL=aztrix-components-chips-edit.mjs.map
