import * as i0 from '@angular/core';
import { EventEmitter, Directive, Input, HostBinding, Output, ViewChild } from '@angular/core';
import { InputSize } from '@ironsource/fusion-ui/components/input/common/base';
import { FormControl } from '@angular/forms';
import { BehaviorSubject, Subject } from 'rxjs';
import { take, takeUntil, map } from 'rxjs/operators';
import { ApiBase } from '@ironsource/fusion-ui/components/api-base';
import * as i1 from '@ironsource/fusion-ui/services/unique-id';
import { isNullOrUndefined } from '@ironsource/fusion-ui/utils';
import { IncludeExcludeTestIdModifiers } from '@ironsource/fusion-ui/entities';
import { TestIdsService } from '@ironsource/fusion-ui/services/test-ids';

const _c0 = ["chipContent"];
const _c1 = ["trigger"];
const CLASS_LIST = [
    'dual-select-button',
    'fu-dual-multi-select-placeholder',
    'dropdown-dual-multi-select-button',
    'clear-all-btn',
    'fu-custom-placeholder',
    'fu-dual-multi-select-placeholder'
];
class DropdownDualMultiSelectBaseComponent extends ApiBase {
    /** @internal */
    set hasSelectAll(value) {
        if (!isNullOrUndefined(value)) {
            this._hasSelectAll = value;
        }
    }
    get hasSelectAll() {
        return this._hasSelectAll;
    }
    set placeholder(data) {
        this.placeholder$.next(data);
        this.defaultPlaceHolder = data;
    }
    /** @internal */
    set searchByProperties(value) {
        this._searchByProperties = value;
    }
    get searchByProperties() {
        return this._searchByProperties;
    }
    /** @internal */
    set opened(data) {
        this.opened$.next(data);
    }
    set items(data) {
        this.items$.next(data || []);
    }
    get items() {
        return this.items$.getValue();
    }
    // backend pagination same like in dropdown component
    /** @internal */
    set backendPagination(value) {
        this.onBackendPaginationChanged(value);
        this.backendPaginationState = value;
    }
    get hasBackendPagination() {
        return !isNullOrUndefined(this.backendPaginationState);
    }
    get testAttribute() {
        return this.testIdsService.getTestAttribute(this.testId, this.testIdIncludeExcludeModifiers.INCLUDE_EXCLUDE);
    }
    constructor(element, renderer, uidService, injector) {
        super();
        this.element = element;
        this.renderer = renderer;
        this.uidService = uidService;
        this.injector = injector;
        this.isDisabled = false;
        /** @internal */
        this.suppressClickButton = false;
        /** @internal */
        this.autoComplete = true;
        /** @internal */
        this.pendingItems = false;
        /** @internal */
        this.testIdIncludeExcludeModifiers = IncludeExcludeTestIdModifiers;
        /** @internal */
        this.testIdsService = this.injector.get(TestIdsService);
        this.scrollDown = new EventEmitter();
        this.searchChange = new EventEmitter();
        this.viewChange = new EventEmitter();
        /** @internal */
        this.preSelectedItems = new FormControl();
        /** @internal */
        this.searchControlTerm = new FormControl('');
        /** @internal */
        this.items$ = new BehaviorSubject([]);
        /** @internal */
        this.opened$ = new BehaviorSubject(false);
        /** @internal */
        this.placeholder$ = new BehaviorSubject('');
        /** @internal */
        this.confirm = false;
        /** @internal */
        this.inputSize = InputSize;
        /** @internal */
        this.dropdownDualMultiSelectionButtonOptions = { rounded: true, size: this.inputSize.Medium };
        /** @internal */
        this.selected$ = new BehaviorSubject('');
        /** @internal */
        this.backendPaginationChanged$ = new Subject();
        this.onDestroy$ = new Subject();
        this.backendPaginationPageNumber = 1;
        this._hasSelectAll = true;
        /** @internal */
        this.loadingLeft$ = new BehaviorSubject(false);
        /** @internal */
        this.propagateChange = (_) => { };
        /** @internal */
        this.propagateTouched = () => { };
        this.uid = this.uidService.getUniqueId().toString();
    }
    ngOnInit() {
        this.selected$.next(this.defaultPlaceHolder);
        this.contentTemplate = this.chipContent;
        this.initializeListeners();
    }
    ngOnDestroy() {
        this.resetState$.complete();
        this.onDestroy$.next();
        this.onDestroy$.complete();
        this.backendPaginationChanged$.next();
        this.backendPaginationChanged$.complete();
    }
    /** @internal */
    onScrollDown() {
        if (this.hasBackendPagination && this.backendPaginationTotalResult && this.backendPaginationTotalResult > this.items.length) {
            this.loadingLeft$.next(true);
            this.backendPaginationState
                .backendGetFunction({
                ...this.backendPaginationState.getOptions,
                pageNumber: this.backendPaginationPageNumber + 1
            })
                .pipe(take(1))
                .subscribe(val => {
                const responseValue = val && Array.isArray(val[this.backendPaginationState.responseDataPropertyName])
                    ? val[this.backendPaginationState.responseDataPropertyName]
                    : [];
                const value = this.backendPaginationState.mappingFunction
                    ? responseValue.map(this.backendPaginationState.mappingFunction)
                    : responseValue;
                const dropdownOptions = this.sortOptions({
                    backendPagination: this.backendPaginationState,
                    leftSideItems: [...value]
                });
                this.items = [...this.items, ...dropdownOptions];
                this.backendPaginationPageNumber++;
            });
        }
        else {
            this.scrollDown.emit();
        }
    }
    /** @internal */
    changeConfig(val) {
        this.element.nativeElement.style.setProperty('--fu-chip-max-width', val);
    }
    /** @internal */
    valueSelected() {
        return this.selected$.pipe(takeUntil(this.onDestroy$), map(value => {
            const partialSelect = {};
            if (!isNullOrUndefined(value) && !value.toString().toLowerCase().startsWith('all ') && !!this.selectedChange?.length) {
                partialSelect['firstSelected'] = this.selectedChange[0];
                partialSelect['totalAmount'] = this.totalItems ?? this.items$.getValue().length;
            }
            return (value !== this.defaultPlaceHolder && value !== 'All selected') || this.selectedTypeObject
                ? {
                    value,
                    isSelected: !!this.selectedChange?.length,
                    selectedCount: this.selectedChange?.length,
                    partialSelect
                }
                : { value: null, isSelected: false };
        }));
    }
    /** @internal */
    open() {
        this.trigger.nativeElement.click();
    }
    /** @internal */
    applySelect(apply = false) {
        this.opened$.next(!apply);
        this.confirm = true;
        this.setLabel();
        this.propagateChange(this.preSelectedItems.value);
        this.selectedChange = Array.isArray(this.preSelectedItems.value) ? [...this.preSelectedItems.value] : this.preSelectedItems.value;
        this.selected$.next(this.selectedChange?.length === 1
            ? this.selectedTypeObject
                ? this.selectedChange[0]
                : this.selectedChange[0]?.displayText || this.selectedChange[0]?.title
            : this.placeholder$.getValue());
        this.searchControlTerm.setValue('');
        this.viewChange.emit(this.opened$.getValue());
    }
    /** @internal */
    closeDropdownDualSelect() {
        this.opened$.next(false);
        this.confirm = false;
        this.writeValue(this.selectedChange);
        this.searchControlTerm.setValue('');
        this.viewChange.emit(this.opened$.getValue());
    }
    /** @internal */
    onClickDualMultiSelectButton() {
        if (!this.isDisabled && !this.suppressClickButton) {
            this.opened$.next(true);
            this.isPositionLeft = this.calcDualMultiSelectHolderPosition();
            this.viewChange.emit(this.opened$.getValue());
        }
    }
    /** @internal */
    writeValue(value) {
        this.preSelectedItems.setValue(value);
        this.selectedChange = value;
        this.selected$.next(value?.length === 1
            ? this.selectedTypeObject
                ? value[0]
                : value[0]?.displayText || value[0]?.title
            : this.placeholder$.getValue());
    }
    /** @internal */
    registerOnChange(fn) {
        this.propagateChange = fn;
    }
    /** @internal */
    registerOnTouched(fn) {
        this.propagateTouched = fn;
    }
    /** @internal */
    setDisabledState(isDisabled) {
        this.isDisabled = isDisabled;
    }
    /** @internal */
    onOutsideClick($event) {
        const regularButtonClicked = !this.dynamicPlaceholder
            ? !($event.closest(`.dual-select-button`)?.id === `${this.uid}-button-regular`)
            : !($event.closest(`.dual-select-button`)?.id === `${this.uid}-button-dynamic`);
        const isClickOutSide = this.templateRef
            ? !$event.closest('fusion-dropdown-dual-multi-select') || !($event.closest(`.is-dropdown-dual-multi-select`)?.id === this.uid)
            : regularButtonClicked;
        const addFilterOptionClicked = !$event.closest('fusion-dropdown-option');
        if (isClickOutSide && addFilterOptionClicked && !$event.closest('.clear-all-btn') && !$event.closest('.icon-clear')) {
            this.closeDropdownDualSelect();
            this.viewChange.emit(this.opened$.getValue());
        }
    }
    calcDualMultiSelectHolderPosition() {
        const hostElement = this.element.nativeElement;
        if (this.parentWithOverflow === undefined || !document.contains(this.parentWithOverflow)) {
            this.parentWithOverflow = this.getParentWithOverflow(hostElement);
        }
        if (this.parentWithOverflow !== null) {
            const parentOverflowRect = this.parentWithOverflow.getBoundingClientRect();
            const hostHolderRect = hostElement.getBoundingClientRect();
            const hasSpaceOnLeft = hostHolderRect.right - parentOverflowRect.left >= 528;
            return hasSpaceOnLeft && parentOverflowRect.right - hostHolderRect.left < 528;
        }
        return false;
    }
    getParentWithOverflow(childEl) {
        const parent = childEl.parentElement;
        let retVal = null;
        if (parent) {
            const parentOverflow = window.getComputedStyle(parent).overflow;
            retVal = ['auto', 'hidden', 'scroll'].includes(parentOverflow) ? parent : this.getParentWithOverflow(parent);
        }
        return retVal;
    }
    changeTerm(term) {
        this.searchChange.emit(term);
    }
    initializeListeners() {
        this.searchControlTerm.valueChanges.pipe(takeUntil(this.onDestroy$)).subscribe(this.changeTerm.bind(this));
        this.preSelectedItems.valueChanges.pipe(takeUntil(this.onDestroy$)).subscribe(this.checkSelectItemsChanged.bind(this));
        this.resetState$
            .asObservable()
            .pipe(takeUntil(this.onDestroy$))
            .subscribe(_ => {
            this.writeValue(null);
            this.propagateChange(null);
        });
        this.selected$
            .asObservable()
            .pipe(takeUntil(this.onDestroy$))
            .subscribe(selected => (this.chipDefaultContent = this.title + ': ' + selected));
    }
    checkSelectItemsChanged(item) {
        // commented bny fix https://ironsrc-mobile.atlassian.net/browse/FU-484
        // if (JSON.stringify(item) !== JSON.stringify(this.selectedChange) && this.confirm) {
        //     this.selectedChange = item;
        // }
        this.setLabel();
    }
    setLabel() {
        let placeholder = this.defaultPlaceHolder;
        if (this.preSelectedItems.value &&
            this.preSelectedItems.value.length > 0 &&
            (this.items$.getValue().length > 0 || this.hasBackendPagination)) {
            const itemName = !!this.selectedItemName
                ? this.preSelectedItems.value.length === 1
                    ? this.selectedItemName.singular
                    : this.selectedItemName.plural
                : '';
            const placeholderPrefix = this.preSelectedItems.value.length === this.items$.getValue().length ? 'All' : `${this.preSelectedItems.value.length}`;
            placeholder = `${placeholderPrefix + (itemName ? ' ' + itemName : '')} selected`;
        }
        this.placeholder$.next(placeholder);
    }
    onBackendPaginationChanged(backendPagination) {
        this.backendPaginationChanged$.next();
        this.backendPaginationTotalResult = null;
        this.backendPaginationPageNumber = 1;
        this.items = null;
        this.loadingLeft$.next(true);
        if (backendPagination) {
            backendPagination
                .backendGetFunction(backendPagination.getOptions)
                .pipe(takeUntil(this.backendPaginationChanged$))
                .subscribe(val => {
                const value = val ? [...val[backendPagination.responseDataPropertyName]] : null;
                this.items = this.sortOptions({
                    backendPagination,
                    leftSideItems: value
                        ? backendPagination.mappingFunction
                            ? value.map(backendPagination.mappingFunction)
                            : value
                        : null
                });
                this.backendPaginationTotalResult = val ? val[backendPagination.responseTotalCountPropertyName] : null;
                this.totalItems = this.backendPaginationTotalResult;
                this.loadingLeft$.next(false);
            });
        }
    }
    sortOptions({ backendPagination, leftSideItems }) {
        if (backendPagination.sortingFunction) {
            return leftSideItems.sort(backendPagination.sortingFunction);
        }
        return leftSideItems;
    }
    static { this.ɵfac = function DropdownDualMultiSelectBaseComponent_Factory(t) { return new (t || DropdownDualMultiSelectBaseComponent)(i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i0.Renderer2), i0.ɵɵdirectiveInject(i1.UniqueIdService), i0.ɵɵdirectiveInject(i0.Injector)); }; }
    static { this.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: DropdownDualMultiSelectBaseComponent, viewQuery: function DropdownDualMultiSelectBaseComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(_c0, 7);
            i0.ɵɵviewQuery(_c1, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.chipContent = _t.first);
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.trigger = _t.first);
        } }, hostVars: 1, hostBindings: function DropdownDualMultiSelectBaseComponent_HostBindings(rf, ctx) { if (rf & 2) {
            i0.ɵɵattribute("data-testid", ctx.testAttribute);
        } }, inputs: { isDisabled: "isDisabled", dynamicPlaceholder: "dynamicPlaceholder", totalItems: "totalItems", suppressClickButton: "suppressClickButton", autoComplete: "autoComplete", title: "title", testId: "testId", pendingItems: "pendingItems", hasSelectAll: "hasSelectAll", placeholder: "placeholder", searchByProperties: "searchByProperties", opened: "opened", items: "items", selectedItemName: "selectedItemName", backendPagination: "backendPagination" }, outputs: { scrollDown: "scrollDown", searchChange: "searchChange", viewChange: "viewChange" }, features: [i0.ɵɵInheritDefinitionFeature] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(DropdownDualMultiSelectBaseComponent, [{
        type: Directive
    }], () => [{ type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i1.UniqueIdService }, { type: i0.Injector }], { isDisabled: [{
            type: Input
        }], dynamicPlaceholder: [{
            type: Input
        }], totalItems: [{
            type: Input
        }], suppressClickButton: [{
            type: Input
        }], autoComplete: [{
            type: Input
        }], title: [{
            type: Input
        }], testId: [{
            type: Input
        }], pendingItems: [{
            type: Input
        }], hasSelectAll: [{
            type: Input
        }], placeholder: [{
            type: Input
        }], searchByProperties: [{
            type: Input
        }], opened: [{
            type: Input
        }], items: [{
            type: Input
        }], selectedItemName: [{
            type: Input
        }], backendPagination: [{
            type: Input
        }], testAttribute: [{
            type: HostBinding,
            args: ['attr.data-testid']
        }], scrollDown: [{
            type: Output
        }], searchChange: [{
            type: Output
        }], viewChange: [{
            type: Output
        }], chipContent: [{
            type: ViewChild,
            args: ['chipContent', { static: true }]
        }], trigger: [{
            type: ViewChild,
            args: ['trigger']
        }] }); })();

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

export { DropdownDualMultiSelectBaseComponent };
//# sourceMappingURL=ironsource-fusion-ui-components-dropdown-dual-multi-select-common-base.mjs.map
