import * as i0 from '@angular/core';
import { EventEmitter, Directive, ContentChildren, ViewChild, Input, Output } from '@angular/core';
import { ChipFilterComponent } from '@ironsource/fusion-ui/components/chip-filter';
import { BehaviorSubject, Subject, combineLatest } from 'rxjs';
import { takeUntil, filter, tap, delay } from 'rxjs/operators';
import { FormControl } from '@angular/forms';

const _c0 = ["addFilter"];
class ChipFiltersBaseComponent {
    /** @internal */
    set chipFilters(value) {
        this._chipFilters = value;
        this.setChipFilters();
    }
    get chipFilters() {
        return this._chipFilters;
    }
    set disableAddFilter(val) {
        this.disableAddFilter$.next(val);
    }
    set addFilterOptions(options) {
        this.optionsRef$.next(options);
        this.options$.next(this.optionsRef$.getValue());
    }
    constructor(renderer, cdr) {
        this.renderer = renderer;
        this.cdr = cdr;
        this.isSearch = false;
        this.selectFilter = new EventEmitter();
        this.dynamicChipSelect = new EventEmitter();
        this.removeSelection = new EventEmitter();
        /** @internal */
        this.disableAddFilter$ = new BehaviorSubject(null);
        /** @internal */
        this.addFilterControl = new FormControl([]);
        /** @internal */
        this.optionsRef$ = new BehaviorSubject([]);
        /** @internal */
        this.options$ = new BehaviorSubject([]);
        /** @internal */
        this.addFilterIcon = 'tune';
        this.selectedFilters = [];
        this.preSelectedDynamicOptions = [];
        this.addedFilters = [];
        this.onDestroy$ = new Subject();
    }
    ngAfterViewInit() {
        this.initDynamicFiltersListeners();
        this.checkForPreSelectedDynamic();
    }
    ngOnDestroy() {
        this.onDestroy$.next();
        this.onDestroy$.complete();
    }
    setChipFilters() {
        this.addFilterIndex = this.chipFilters.length;
        this.setPreSelectedFilters();
        this.orderChipFilters(this.chipFilters);
        this.initListeners();
    }
    initListeners() {
        this.onTypeChipsChanges();
        this.onSelectedValueListener();
        this.onClosedChipListener();
    }
    checkForPreSelectedDynamic() {
        this.preSelectedDynamicOptions = this.chipFilters
            .filter(chip => !!chip['chipSelectValue'] && chip.mode === 'dynamic')
            .map(chip => {
            const dynamicOptions = this.options$.getValue().filter(option => {
                return chip['chipSelectValue'].id === option.id;
            });
            return dynamicOptions.length ? dynamicOptions[0] : null;
        })
            .filter(Boolean);
        if (this.preSelectedDynamicOptions.length) {
            this.addFilterControl.setValue(this.preSelectedDynamicOptions);
        }
    }
    initDynamicFiltersListeners() {
        this.addFilterControl.valueChanges
            .pipe(takeUntil(this.onDestroy$), filter(options => Array.isArray(options)), tap(options => this.dynamicChipSelect.emit(options[0])), delay(50))
            .subscribe((options) => {
            options.forEach(option => {
                this.openAddedDynamicFilter(option);
            });
        });
    }
    onTypeChipsChanges() {
        const chipTypes = this.chipFilters.map(chip => chip.chipType$.asObservable());
        combineLatest(chipTypes)
            .pipe(takeUntil(this.onDestroy$))
            .subscribe(_ => {
            this.chipFilters.notifyOnChanges();
        });
        this.chipFilters.changes.pipe(takeUntil(this.onDestroy$)).subscribe((chips) => {
            this.orderChipFilters(chips);
        });
    }
    onSelectedValueListener() {
        this.chipFilters.forEach(chip => {
            chip.selectedChange.pipe(takeUntil(this.onDestroy$)).subscribe(val => {
                const isSelected = this.selectedFilters.some(selectedChip => selectedChip.id === val.id);
                this.selectedFilters = isSelected
                    ? this.selectedFilters.map(filter => (filter.id === val.id ? val : filter))
                    : [...this.selectedFilters, val];
                this.selectFilter.emit(this.selectedFilters);
            });
        });
    }
    onClosedChipListener() {
        this.chipFilters.forEach(chip => chip.onRemove.pipe(takeUntil(this.onDestroy$)).subscribe(val => {
            this.selectedFilters = this.selectedFilters.filter(selectedChip => {
                if (val.id !== selectedChip.id) {
                    return selectedChip;
                }
            });
            this.addedFilters = this.addedFilters.filter(filterChip => {
                if (val.id === filterChip.id) {
                    this.restoredUnselectedFiltersOptions(filterChip, chip.mode === 'dynamic');
                }
                return val.id !== filterChip.id;
            });
            this.removeSelection.emit(this.selectedFilters);
            this.addFilterControl.reset();
        }));
    }
    openAddedDynamicFilter(option) {
        this.chipFilters.toArray().forEach(chip => {
            const isSelected = this.addedFilters.some(selectedChip => selectedChip.id === chip['id']);
            if (chip['id'] === option.id && !isSelected && chip.mode === 'dynamic') {
                const isPreSelected = this.preSelectedDynamicOptions.some(item => item.id === option.id);
                const newSelection = {
                    id: option.id,
                    value: option,
                    isSelected: chip.selected
                };
                this.addedFilters = [...this.addedFilters, newSelection];
                this.reduceSelectedFiltersOptions();
                if (!isPreSelected) {
                    chip.apiBase.open();
                    this.cdr.markForCheck();
                }
                else {
                    this.preSelectedDynamicOptions = this.preSelectedDynamicOptions.filter(item => item.id !== option.id);
                }
            }
            else {
                this.addFilterControl.reset();
            }
        });
    }
    orderChipFilters(chipFilters) {
        chipFilters.forEach((chip, index) => {
            switch (chip.chipType$.getValue()) {
                case 'RemoveAbleSelect':
                    this.renderer.setStyle(chip.element.nativeElement, 'order', `-${chipFilters.length - index}`);
                    break;
                case 'UnRemoveAbleSelect':
                    this.renderer.setStyle(chip.element.nativeElement, 'order', `-${2 * chipFilters.length - index}`);
                    break;
                default:
                    this.renderer.setStyle(chip.element.nativeElement, 'order', `${index}`);
            }
        });
    }
    setPreSelectedFilters() {
        const preSelectedChip = this.chipFilters.filter(chip => !!chip['chipSelectValue']);
        this.selectedFilters = preSelectedChip.map(chip => chip['chipSelectValue']);
    }
    reduceSelectedFiltersOptions() {
        const selectedValues = this.addedFilters.filter(selectedChip => selectedChip?.value);
        const newOptions = this.optionsRef$.getValue().filter(option => !selectedValues.some(select => select.id === option.id));
        this.options$.next(newOptions);
    }
    restoredUnselectedFiltersOptions(selectedChip, isDynamic) {
        if (isDynamic) {
            const removedChip = this.optionsRef$.getValue().filter(option => option.id === selectedChip.id)[0];
            const restoredOptions = this.options$.getValue().concat([removedChip]);
            const sortedRestoredOptions = restoredOptions.sort((a, b) => (a.id > b.id ? 1 : -1));
            this.options$.next([...sortedRestoredOptions]);
        }
    }
    static { this.ɵfac = function ChipFiltersBaseComponent_Factory(t) { return new (t || ChipFiltersBaseComponent)(i0.ɵɵdirectiveInject(i0.Renderer2), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef)); }; }
    static { this.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: ChipFiltersBaseComponent, contentQueries: function ChipFiltersBaseComponent_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) {
            i0.ɵɵcontentQuery(dirIndex, ChipFilterComponent, 4);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.chipFilters = _t);
        } }, viewQuery: function ChipFiltersBaseComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(_c0, 7);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.addFilterComponent = _t.first);
        } }, inputs: { disableAddFilter: "disableAddFilter", testId: "testId", addFilterOptions: "addFilterOptions", addFiltersTitle: "addFiltersTitle", isSearch: "isSearch" }, outputs: { selectFilter: "selectFilter", dynamicChipSelect: "dynamicChipSelect", removeSelection: "removeSelection" } }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ChipFiltersBaseComponent, [{
        type: Directive
    }], () => [{ type: i0.Renderer2 }, { type: i0.ChangeDetectorRef }], { chipFilters: [{
            type: ContentChildren,
            args: [ChipFilterComponent]
        }], addFilterComponent: [{
            type: ViewChild,
            args: ['addFilter', { static: true }]
        }], disableAddFilter: [{
            type: Input
        }], testId: [{
            type: Input
        }], addFilterOptions: [{
            type: Input
        }], addFiltersTitle: [{
            type: Input
        }], isSearch: [{
            type: Input
        }], selectFilter: [{
            type: Output
        }], dynamicChipSelect: [{
            type: Output
        }], removeSelection: [{
            type: Output
        }] }); })();

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

export { ChipFiltersBaseComponent };
//# sourceMappingURL=ironsource-fusion-ui-components-chip-filters-common-base.mjs.map
