import * as i0 from '@angular/core';
import { input, signal, inject, effect, ViewChild, HostBinding, ChangeDetectionStrategy, Component } from '@angular/core';
import { Validators, NgControl } from '@angular/forms';
import * as i1 from 'primeng/picklist';
import { PickListModule } from 'primeng/picklist';
import { FieldValidation } from '@masterteam/components/field-validation';
import { isInvalid } from '@masterteam/components';
import * as i2 from 'primeng/api';

class PickListField {
    label = input(...(ngDevMode ? [undefined, { debugName: "label" }] : []));
    class = input('', ...(ngDevMode ? [{ debugName: "class" }] : []));
    readonly = input(false, ...(ngDevMode ? [{ debugName: "readonly" }] : []));
    options = input([], ...(ngDevMode ? [{ debugName: "options" }] : []));
    optionLabel = input('label', ...(ngDevMode ? [{ debugName: "optionLabel" }] : []));
    optionValue = input('value', ...(ngDevMode ? [{ debugName: "optionValue" }] : []));
    sourceHeader = input('Available', ...(ngDevMode ? [{ debugName: "sourceHeader" }] : []));
    targetHeader = input('Selected', ...(ngDevMode ? [{ debugName: "targetHeader" }] : []));
    showSourceControls = input(true, ...(ngDevMode ? [{ debugName: "showSourceControls" }] : []));
    showTargetControls = input(true, ...(ngDevMode ? [{ debugName: "showTargetControls" }] : []));
    showSourceFilter = input(false, ...(ngDevMode ? [{ debugName: "showSourceFilter" }] : []));
    showTargetFilter = input(false, ...(ngDevMode ? [{ debugName: "showTargetFilter" }] : []));
    filterBy = input(...(ngDevMode ? [undefined, { debugName: "filterBy" }] : []));
    dataKey = input(...(ngDevMode ? [undefined, { debugName: "dataKey" }] : []));
    filterLocale = input(...(ngDevMode ? [undefined, { debugName: "filterLocale" }] : []));
    filterMatchMode = input('contains', ...(ngDevMode ? [{ debugName: "filterMatchMode" }] : []));
    dragdrop = input(false, ...(ngDevMode ? [{ debugName: "dragdrop" }] : []));
    responsive = input(true, ...(ngDevMode ? [{ debugName: "responsive" }] : []));
    required = input(false, ...(ngDevMode ? [{ debugName: "required" }] : []));
    styleClass = '';
    requiredValidator = Validators.required;
    value = signal([], ...(ngDevMode ? [{ debugName: "value" }] : []));
    targetItems = signal([], ...(ngDevMode ? [{ debugName: "targetItems" }] : []));
    sourceItems = signal([], ...(ngDevMode ? [{ debugName: "sourceItems" }] : []));
    disabled = signal(false, ...(ngDevMode ? [{ debugName: "disabled" }] : []));
    onTouched = () => { };
    onModelChange = () => { };
    ngControl = inject(NgControl, { self: true });
    isInvalid = isInvalid;
    hasInitialized = false;
    pickList;
    constructor() {
        if (this.ngControl) {
            this.ngControl.valueAccessor = this;
        }
        effect(() => {
            if (this.ngControl?.control && this.required()) {
                this.ngControl.control.addValidators(Validators.required);
                this.ngControl.control.updateValueAndValidity();
            }
        });
        effect(() => {
            this.options();
            if (this.hasInitialized) {
                this.syncLists();
            }
        });
    }
    ngOnInit() {
        this.styleClass = this.class();
        this.syncLists();
        this.hasInitialized = true;
    }
    writeValue(value) {
        const nextValue = Array.isArray(value)
            ? [...value]
            : value === null || value === undefined
                ? []
                : [value];
        this.value.set(nextValue);
        this.syncLists();
    }
    registerOnChange(fn) {
        this.onModelChange = fn;
    }
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    setDisabledState(disabled) {
        this.disabled.set(disabled);
    }
    onInteractiveChange() {
        this.syncFromPickList();
    }
    handleBlur() {
        this.onTouched();
    }
    displayLabel(item) {
        if (item === null || item === undefined) {
            return '';
        }
        if (typeof item === 'string' || typeof item === 'number') {
            return String(item);
        }
        const labelKey = this.optionLabel();
        if (labelKey && item[labelKey] !== undefined) {
            return item[labelKey];
        }
        return JSON.stringify(item);
    }
    syncLists() {
        const currentValue = this.value();
        const targetOptions = this.normalizeValueToOptions(currentValue);
        this.targetItems.set(targetOptions);
        this.updateSourceFromTarget(targetOptions);
    }
    syncFromPickList() {
        const pickListInstance = this.pickList;
        if (!pickListInstance) {
            return;
        }
        const currentTarget = [...(pickListInstance.target() ?? [])];
        const currentSource = [...(pickListInstance.source() ?? [])];
        this.targetItems.set(currentTarget);
        this.sourceItems.set(currentSource);
        const newValue = this.extractValues(currentTarget);
        this.value.set(newValue);
        this.onModelChange(newValue);
        this.onTouched();
    }
    normalizeValueToOptions(value) {
        if (!Array.isArray(value)) {
            return [];
        }
        return value
            .map((entry) => this.findOption(entry) ?? entry)
            .filter((item) => item !== undefined && item !== null);
    }
    extractValues(items) {
        const optionValueKey = this.optionValue();
        if (!optionValueKey) {
            return items ?? [];
        }
        const values = [];
        (items ?? []).forEach((item) => {
            if (item && typeof item === 'object') {
                values.push(item[optionValueKey] ?? item);
            }
            else {
                values.push(item);
            }
        });
        return values;
    }
    updateSourceFromTarget(targetItems) {
        const options = this.options() ?? [];
        const targetIds = new Set((targetItems ?? []).map((item) => this.getIdentifier(item)));
        const newSource = options.filter((option) => !targetIds.has(this.getIdentifier(option)));
        this.sourceItems.set(newSource);
    }
    getIdentifier(item) {
        if (item === null || item === undefined) {
            return item;
        }
        const optionValueKey = this.optionValue();
        if (!optionValueKey) {
            return item;
        }
        if (typeof item === 'object') {
            return item[optionValueKey];
        }
        return item;
    }
    findOption(entry) {
        const options = this.options() ?? [];
        const entryId = this.getIdentifier(entry);
        return options.find((option) => this.getIdentifier(option) === entryId);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.3", ngImport: i0, type: PickListField, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.0.3", type: PickListField, isStandalone: true, selector: "mt-pick-list-field", inputs: { label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, class: { classPropertyName: "class", publicName: "class", isSignal: true, isRequired: false, transformFunction: null }, readonly: { classPropertyName: "readonly", publicName: "readonly", isSignal: true, isRequired: false, transformFunction: null }, options: { classPropertyName: "options", publicName: "options", isSignal: true, isRequired: false, transformFunction: null }, optionLabel: { classPropertyName: "optionLabel", publicName: "optionLabel", isSignal: true, isRequired: false, transformFunction: null }, optionValue: { classPropertyName: "optionValue", publicName: "optionValue", isSignal: true, isRequired: false, transformFunction: null }, sourceHeader: { classPropertyName: "sourceHeader", publicName: "sourceHeader", isSignal: true, isRequired: false, transformFunction: null }, targetHeader: { classPropertyName: "targetHeader", publicName: "targetHeader", isSignal: true, isRequired: false, transformFunction: null }, showSourceControls: { classPropertyName: "showSourceControls", publicName: "showSourceControls", isSignal: true, isRequired: false, transformFunction: null }, showTargetControls: { classPropertyName: "showTargetControls", publicName: "showTargetControls", isSignal: true, isRequired: false, transformFunction: null }, showSourceFilter: { classPropertyName: "showSourceFilter", publicName: "showSourceFilter", isSignal: true, isRequired: false, transformFunction: null }, showTargetFilter: { classPropertyName: "showTargetFilter", publicName: "showTargetFilter", isSignal: true, isRequired: false, transformFunction: null }, filterBy: { classPropertyName: "filterBy", publicName: "filterBy", isSignal: true, isRequired: false, transformFunction: null }, dataKey: { classPropertyName: "dataKey", publicName: "dataKey", isSignal: true, isRequired: false, transformFunction: null }, filterLocale: { classPropertyName: "filterLocale", publicName: "filterLocale", isSignal: true, isRequired: false, transformFunction: null }, filterMatchMode: { classPropertyName: "filterMatchMode", publicName: "filterMatchMode", isSignal: true, isRequired: false, transformFunction: null }, dragdrop: { classPropertyName: "dragdrop", publicName: "dragdrop", isSignal: true, isRequired: false, transformFunction: null }, responsive: { classPropertyName: "responsive", publicName: "responsive", isSignal: true, isRequired: false, transformFunction: null }, required: { classPropertyName: "required", publicName: "required", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "class": "this.styleClass" }, classAttribute: "grid gap-1" }, viewQueries: [{ propertyName: "pickList", first: true, predicate: ["pickList"], descendants: true }], ngImport: i0, template: "@if (label()) {\r\n  <label\r\n    [class.required]=\"ngControl?.control?.hasValidator(requiredValidator)\"\r\n    [for]=\"ngControl?.name || label()\"\r\n    >{{ label() }}</label\r\n  >\r\n}\r\n<p-pickList\r\n  #pickList\r\n  [source]=\"sourceItems()\"\r\n  [target]=\"targetItems()\"\r\n  (onMoveToTarget)=\"onInteractiveChange()\"\r\n  (onMoveToSource)=\"onInteractiveChange()\"\r\n  (onMoveAllToTarget)=\"onInteractiveChange()\"\r\n  (onMoveAllToSource)=\"onInteractiveChange()\"\r\n  (onTargetReorder)=\"onInteractiveChange()\"\r\n  (onSourceReorder)=\"onInteractiveChange()\"\r\n  (onBlur)=\"handleBlur()\"\r\n  [filterBy]=\"filterBy() || optionLabel()\"\r\n  [showSourceControls]=\"showSourceControls()\"\r\n  [showTargetControls]=\"showTargetControls()\"\r\n  [showSourceFilter]=\"showSourceFilter()\"\r\n  [showTargetFilter]=\"showTargetFilter()\"\r\n  [sourceHeader]=\"sourceHeader()\"\r\n  [targetHeader]=\"targetHeader()\"\r\n  [dragdrop]=\"dragdrop()\"\r\n  [responsive]=\"responsive()\"\r\n  [disabled]=\"disabled() || readonly()\"\r\n  [styleClass]=\"'w-full relative'\"\r\n  [class.p-invalid]=\"isInvalid(ngControl?.control)\"\r\n>\r\n  <ng-template let-item pTemplate=\"item\">\r\n    {{ displayLabel(item) }}\r\n  </ng-template>\r\n</p-pickList>\r\n\r\n<mt-field-validation [control]=\"ngControl?.control\"></mt-field-validation>\r\n", styles: [":host{display:block}\n"], dependencies: [{ kind: "ngmodule", type: PickListModule }, { kind: "component", type: i1.PickList, selector: "p-pickList, p-picklist, p-pick-list", inputs: ["hostName", "source", "target", "dataKey", "sourceHeader", "tabindex", "rightButtonAriaLabel", "leftButtonAriaLabel", "allRightButtonAriaLabel", "allLeftButtonAriaLabel", "upButtonAriaLabel", "downButtonAriaLabel", "topButtonAriaLabel", "bottomButtonAriaLabel", "sourceAriaLabel", "targetAriaLabel", "targetHeader", "responsive", "filterBy", "filterLocale", "trackBy", "sourceTrackBy", "targetTrackBy", "showSourceFilter", "showTargetFilter", "metaKeySelection", "dragdrop", "style", "styleClass", "sourceStyle", "targetStyle", "showSourceControls", "showTargetControls", "sourceFilterPlaceholder", "targetFilterPlaceholder", "disabled", "sourceOptionDisabled", "targetOptionDisabled", "ariaSourceFilterLabel", "ariaTargetFilterLabel", "filterMatchMode", "stripedRows", "keepSelection", "scrollHeight", "autoOptionFocus", "buttonProps", "moveUpButtonProps", "moveTopButtonProps", "moveDownButtonProps", "moveBottomButtonProps", "moveToTargetProps", "moveAllToTargetProps", "moveToSourceProps", "moveAllToSourceProps", "breakpoint"], outputs: ["sourceChange", "targetChange", "onMoveToSource", "onMoveAllToSource", "onMoveAllToTarget", "onMoveToTarget", "onSourceReorder", "onTargetReorder", "onSourceSelect", "onTargetSelect", "onSourceFilter", "onTargetFilter", "onFocus", "onBlur"] }, { kind: "directive", type: i2.PrimeTemplate, selector: "[pTemplate]", inputs: ["type", "pTemplate"] }, { kind: "component", type: FieldValidation, selector: "mt-field-validation", inputs: ["control", "touched"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.3", ngImport: i0, type: PickListField, decorators: [{
            type: Component,
            args: [{ selector: 'mt-pick-list-field', imports: [PickListModule, FieldValidation], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        class: 'grid gap-1',
                    }, template: "@if (label()) {\r\n  <label\r\n    [class.required]=\"ngControl?.control?.hasValidator(requiredValidator)\"\r\n    [for]=\"ngControl?.name || label()\"\r\n    >{{ label() }}</label\r\n  >\r\n}\r\n<p-pickList\r\n  #pickList\r\n  [source]=\"sourceItems()\"\r\n  [target]=\"targetItems()\"\r\n  (onMoveToTarget)=\"onInteractiveChange()\"\r\n  (onMoveToSource)=\"onInteractiveChange()\"\r\n  (onMoveAllToTarget)=\"onInteractiveChange()\"\r\n  (onMoveAllToSource)=\"onInteractiveChange()\"\r\n  (onTargetReorder)=\"onInteractiveChange()\"\r\n  (onSourceReorder)=\"onInteractiveChange()\"\r\n  (onBlur)=\"handleBlur()\"\r\n  [filterBy]=\"filterBy() || optionLabel()\"\r\n  [showSourceControls]=\"showSourceControls()\"\r\n  [showTargetControls]=\"showTargetControls()\"\r\n  [showSourceFilter]=\"showSourceFilter()\"\r\n  [showTargetFilter]=\"showTargetFilter()\"\r\n  [sourceHeader]=\"sourceHeader()\"\r\n  [targetHeader]=\"targetHeader()\"\r\n  [dragdrop]=\"dragdrop()\"\r\n  [responsive]=\"responsive()\"\r\n  [disabled]=\"disabled() || readonly()\"\r\n  [styleClass]=\"'w-full relative'\"\r\n  [class.p-invalid]=\"isInvalid(ngControl?.control)\"\r\n>\r\n  <ng-template let-item pTemplate=\"item\">\r\n    {{ displayLabel(item) }}\r\n  </ng-template>\r\n</p-pickList>\r\n\r\n<mt-field-validation [control]=\"ngControl?.control\"></mt-field-validation>\r\n", styles: [":host{display:block}\n"] }]
        }], ctorParameters: () => [], propDecorators: { label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], class: [{ type: i0.Input, args: [{ isSignal: true, alias: "class", required: false }] }], readonly: [{ type: i0.Input, args: [{ isSignal: true, alias: "readonly", required: false }] }], options: [{ type: i0.Input, args: [{ isSignal: true, alias: "options", required: false }] }], optionLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "optionLabel", required: false }] }], optionValue: [{ type: i0.Input, args: [{ isSignal: true, alias: "optionValue", required: false }] }], sourceHeader: [{ type: i0.Input, args: [{ isSignal: true, alias: "sourceHeader", required: false }] }], targetHeader: [{ type: i0.Input, args: [{ isSignal: true, alias: "targetHeader", required: false }] }], showSourceControls: [{ type: i0.Input, args: [{ isSignal: true, alias: "showSourceControls", required: false }] }], showTargetControls: [{ type: i0.Input, args: [{ isSignal: true, alias: "showTargetControls", required: false }] }], showSourceFilter: [{ type: i0.Input, args: [{ isSignal: true, alias: "showSourceFilter", required: false }] }], showTargetFilter: [{ type: i0.Input, args: [{ isSignal: true, alias: "showTargetFilter", required: false }] }], filterBy: [{ type: i0.Input, args: [{ isSignal: true, alias: "filterBy", required: false }] }], dataKey: [{ type: i0.Input, args: [{ isSignal: true, alias: "dataKey", required: false }] }], filterLocale: [{ type: i0.Input, args: [{ isSignal: true, alias: "filterLocale", required: false }] }], filterMatchMode: [{ type: i0.Input, args: [{ isSignal: true, alias: "filterMatchMode", required: false }] }], dragdrop: [{ type: i0.Input, args: [{ isSignal: true, alias: "dragdrop", required: false }] }], responsive: [{ type: i0.Input, args: [{ isSignal: true, alias: "responsive", required: false }] }], required: [{ type: i0.Input, args: [{ isSignal: true, alias: "required", required: false }] }], styleClass: [{
                type: HostBinding,
                args: ['class']
            }], pickList: [{
                type: ViewChild,
                args: ['pickList']
            }] } });

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

export { PickListField };
//# sourceMappingURL=masterteam-components-pick-list-field.mjs.map
