import * as i0 from '@angular/core';
import { Component, ChangeDetectionStrategy, NgModule } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import * as i2 from '@aztrix/components/overlay';
import * as i11 from '@aztrix/helpers';
import { iconNameForContextType, PropertyFormControl, CustomValidators, isPhoneRelated, dummyPropertyForType, ContextBuilder, contextServerRepresentation, getContexts, propertyServerRepresentation, getProperties, updateContextInProfileMapper, isOfType, possibleContextsForMissingPropertyType, HelperPipesModule } from '@aztrix/helpers';
import * as i1 from '@aztrix/sdk';
import { throwError, of } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import * as i3 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i4 from '@aztrix/icons';
import { IconsModule } from '@aztrix/icons';
import * as i5 from '@aztrix/components/property-edit';
import { PropertyEditModule } from '@aztrix/components/property-edit';
import * as i6 from '@aztrix/components/snackbar';
import { SnackbarModule } from '@aztrix/components/snackbar';
import * as i7 from '@aztrix/components/button';
import { ButtonModule } from '@aztrix/components/button';
import * as i8 from '@angular/material/form-field';
import * as i9 from '@angular/material/select';
import { MatSelectModule } from '@angular/material/select';
import * as i10 from '@angular/material/core';
import { OverlayModule } from '@angular/cdk/overlay';

class CreatePropertyComponent {
    constructor(_profilesService, _contextsService, _changeDetector, _overlay) {
        this._profilesService = _profilesService;
        this._contextsService = _contextsService;
        this._changeDetector = _changeDetector;
        this._overlay = _overlay;
        this.iconNameForContextType = iconNameForContextType;
        this.form = new UntypedFormGroup({});
        this.saveOnAny = false;
    }
    ngOnInit() {
        if (this.property) {
            this.form = PropertyFormControl.create(this.property, [
                CustomValidators.propertyRequired,
                CustomValidators.propertyValid,
            ]);
            this._updatePossibleContexts();
        }
        else {
            this.possibleContexts = [];
        }
    }
    ngAfterViewInit() {
        if (!isPhoneRelated(this.property?.type)) {
            this.form.markAsTouched();
        }
    }
    changeProperty(changeEvent) {
        if (changeEvent.value) {
            const newProperty = dummyPropertyForType(changeEvent.value);
            newProperty.value =
                this.property && this.property.value ? this.property.value : newProperty.value;
            this.property = newProperty;
            this.form = PropertyFormControl.create(newProperty, [
                CustomValidators.propertyRequired,
                CustomValidators.propertyValid,
            ]);
            this._updatePossibleContexts();
            this._changeDetector.markForCheck();
        }
    }
    selectContext(context) {
        for (const c of this.possibleContexts) {
            c.selected = c.context === context;
        }
        this._changeDetector.markForCheck();
    }
    executeSaveAction() {
        return this._savePropertyToProfile().pipe(catchError((error) => {
            this.error = 'error.default.title';
            this._changeDetector.markForCheck();
            return throwError(error);
        }), tap((tuple) => {
            if (this.didCreate) {
                this.didCreate(tuple?.property);
            }
            this._overlay.closeModal();
        }));
    }
    _savePropertyToProfile() {
        let context = this.selectedContext();
        if (context) {
            if (!context.id) {
                context = ContextBuilder.fromContext(context)
                    .setLabel('') // Clear the label if the selected context does not exist
                    .setProperties([this.form.value]) // Create the context with the property
                    .build();
                return this._profilesService
                    .addContext(this.profile.id, contextServerRepresentation(context))
                    .pipe(map((newContext) => {
                    const newProfile = {
                        ...this.profile,
                        propertyContexts: (getContexts(this.profile).concat(newContext)),
                    };
                    return { profile: newProfile, context: newContext };
                }))
                    .pipe(map((tuple) => ({
                    property: tuple.context.properties?.[0],
                    context: tuple.context,
                })));
            }
            else {
                return this._contextsService
                    .addProperty(context.id, propertyServerRepresentation(this.form.value))
                    .pipe(map((newProperty) => {
                    const newContext = ContextBuilder.fromContext(context)
                        .setProperties(getProperties(context).concat(newProperty))
                        .build();
                    const newProfile = updateContextInProfileMapper(this.profile, context, newContext);
                    return { profile: newProfile, context: newContext, property: newProperty };
                }))
                    .pipe(map(({ context, property }) => ({
                    property: property,
                    context: context,
                })));
            }
        }
        else {
            return of(undefined);
        }
    }
    _selectInitialContext() {
        const context = this.context;
        // Select the first possible context if not requested context
        if (!context) {
            this.selectContext(this.possibleContexts[0].context);
        }
        else if (context.label) {
            // A specific context label is given
            const contextWithLabel = this.possibleContexts.find((object) => isOfType(object.context, context.type) && object.context.label === context.label);
            if (contextWithLabel) {
                this.selectContext(contextWithLabel.context);
            }
            else {
                this.selectContext(this.possibleContexts[0].context);
            }
        }
        else {
            // Find the first context of type
            const contextWithType = this.possibleContexts.find((possibleContext) => isOfType(possibleContext.context, context.type));
            if (contextWithType) {
                this.selectContext(contextWithType.context);
            }
            else {
                // Select the first possible context
                this.selectContext(this.possibleContexts[0].context);
            }
        }
    }
    selectedContext() {
        return this.possibleContexts
            .filter((object) => object.selected)
            .map((object) => object.context)
            .pop();
    }
    _updatePossibleContexts() {
        // Calculate the possible contexts
        this.possibleContexts = (possibleContextsForMissingPropertyType(this.property.type, this.profile).map((context) => ({
            context,
            selected: false,
        })));
        // Select the initial context
        this._selectInitialContext();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: CreatePropertyComponent, deps: [{ token: i1.ProfilesService }, { token: i1.ContextsService }, { token: i0.ChangeDetectorRef }, { token: i2.OverlayService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "17.3.12", type: CreatePropertyComponent, selector: "ng-component", ngImport: i0, template: "<div class=\"c-modal__section\">\n  <ax-snackbar [open]=\"!!error\" color=\"red\" (didClose)=\"error = ''\">{{\n    error | translate\n  }}</ax-snackbar>\n  <!--property value edit view-->\n  <div class=\"c-modal__input-wrapper\">\n    <ng-template #option let-propertyType>\n      <div class=\"property-option\">\n        <ax-icon class=\"icon\" [name]=\"propertyType | propertyIcon\"></ax-icon>\n        <span>{{ propertyType | propertyTypeLabel }}</span>\n      </div>\n    </ng-template>\n\n    <mat-form-field\n      *ngIf=\"selectablePropertyTypes\"\n      style=\"width: 100%\"\n      class=\"c-input\"\n      appearance=\"outline\"\n    >\n      <mat-select\n        (selectionChange)=\"changeProperty($event)\"\n        [value]=\"property.type\"\n        [required]=\"true\"\n        disableOptionCentering\n      >\n        <mat-select-trigger>\n          <ng-container *ngIf=\"!property.type\">\n            {{ 'label.none' | translate }}\n          </ng-container>\n          <ng-container *ngIf=\"property.type\">\n            <ng-container\n              *ngTemplateOutlet=\"option; context: {$implicit: property.type}\"\n            ></ng-container>\n          </ng-container>\n        </mat-select-trigger>\n        <mat-option [value]=\"null\" (click)=\"(property === null)\">\n          {{ 'label.none' | translate }}\n        </mat-option>\n        <mat-option *ngFor=\"let propertyType of selectablePropertyTypes\" [value]=\"propertyType\">\n          <ng-container\n            *ngTemplateOutlet=\"option; context: {$implicit: propertyType}\"\n          ></ng-container>\n        </mat-option>\n      </mat-select>\n      <mat-error>{{ 'label.required' | translate }}</mat-error>\n    </mat-form-field>\n\n    <ax-property-edit\n      *ngIf=\"form && form.value !== {}\"\n      [form]=\"form\"\n      [autofocus]=\"true\"\n    ></ax-property-edit>\n  </div>\n\n  <!--destination context-->\n  <div *ngIf=\"!saveOnAny\">\n    <div class=\"c-modal__section-title underline\">\n      {{ 'modal.missingProperty.context.title' | translate }}\n    </div>\n    <div class=\"list-row-wrapper\" *ngFor=\"let possibleContext of possibleContexts\">\n      <div\n        class=\"m-list-row\"\n        [class.is-selected]=\"possibleContext.selected\"\n        (click)=\"selectContext(possibleContext.context)\"\n      >\n        <ax-icon\n          class=\"icon c-settings__context-icon\"\n          [name]=\"iconNameForContextType(possibleContext.context.type)\"\n        ></ax-icon>\n\n        <div class=\"m-list-row__cell-middle\">\n          <span class=\"c-settings__context-label\">{{\n            possibleContext.context.id\n              ? (possibleContext.context | contextDisplayLabel)\n              : ('label.new' | translate: {word: possibleContext.context | contextDisplayLabel})\n          }}</span>\n        </div>\n        <div class=\"m-list-row__cell-last\">\n          <ax-icon *ngIf=\"possibleContext.selected\" class=\"icon green-text\" name=\"check\"></ax-icon>\n        </div>\n      </div>\n    </div>\n  </div>\n\n  <!--save-->\n  <div class=\"h-button-wrapper\">\n    <button\n      axButton\n      [axAutoDisableButton]=\"executeSaveAction()\"\n      [disabled]=\"form.invalid\"\n      class=\"cy-save\"\n      color=\"primary\"\n      filled\n    >\n      {{ 'label.save' | translate }}\n    </button>\n  </div>\n</div>\n", styles: [":host .h-button-wrapper{padding:1rem}.c-modal__section-title{padding-bottom:0}.list-row-wrapper{margin:0 1rem}.m-list-row{min-height:auto}.m-list-row .m-list-row__cell-middle{max-width:calc(100% - 20px)}.m-list-row .m-list-row__cell-last{display:flex}.property-edit{display:grid;grid-template-columns:7rem 1fr;grid-gap:1rem}.property-option{display:flex;align-items:center;color:#555}.property-option .icon{margin-right:.5rem}.property-option .icon{width:1rem;height:1rem}\n"], dependencies: [{ kind: "directive", type: i3.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i3.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "component", type: i4.IconComponent, selector: "ax-icon", inputs: ["name", "inline"] }, { kind: "component", type: i5.PropertyEditComponent, selector: "ax-property-edit", inputs: ["isIndividual", "isProposalSubscribeForm"] }, { kind: "component", type: i6.SnackbarComponent, selector: "ax-snackbar", inputs: ["type", "timeout", "dismissible", "open", "icon", "color"], outputs: ["didClose"] }, { kind: "directive", type: i7.ButtonDirective, selector: "[axButton]", inputs: ["color", "labelHideMobile", "smallButton", "bigButton", "fullWidth", "filled", "outline", "icon-button", "hoverLabel", "hover", "lowercase", "disabled"] }, { kind: "directive", type: i7.AutoDisableButtonDirective, selector: "[axAutoDisableButton]", inputs: ["axAutoDisableButton", "enabled"], outputs: ["axAutoDisableButtonChange", "axAutoDisableButtonError"] }, { kind: "component", type: i8.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i8.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "component", type: i9.MatSelect, selector: "mat-select", inputs: ["aria-describedby", "panelClass", "disabled", "disableRipple", "tabIndex", "hideSingleSelectionIndicator", "placeholder", "required", "multiple", "disableOptionCentering", "compareWith", "value", "aria-label", "aria-labelledby", "errorStateMatcher", "typeaheadDebounceInterval", "sortComparator", "id", "panelWidth"], outputs: ["openedChange", "opened", "closed", "selectionChange", "valueChange"], exportAs: ["matSelect"] }, { kind: "directive", type: i9.MatSelectTrigger, selector: "mat-select-trigger" }, { kind: "component", type: i10.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "pipe", type: i11.PropertyTypeLabelPipe, name: "propertyTypeLabel" }, { kind: "pipe", type: i11.PropertyIconPipe, name: "propertyIcon" }, { kind: "pipe", type: i11.ContextDisplayLabelPipe, name: "contextDisplayLabel" }, { kind: "pipe", type: i11.TranslatePipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: CreatePropertyComponent, decorators: [{
            type: Component,
            args: [{ changeDetection: ChangeDetectionStrategy.OnPush, template: "<div class=\"c-modal__section\">\n  <ax-snackbar [open]=\"!!error\" color=\"red\" (didClose)=\"error = ''\">{{\n    error | translate\n  }}</ax-snackbar>\n  <!--property value edit view-->\n  <div class=\"c-modal__input-wrapper\">\n    <ng-template #option let-propertyType>\n      <div class=\"property-option\">\n        <ax-icon class=\"icon\" [name]=\"propertyType | propertyIcon\"></ax-icon>\n        <span>{{ propertyType | propertyTypeLabel }}</span>\n      </div>\n    </ng-template>\n\n    <mat-form-field\n      *ngIf=\"selectablePropertyTypes\"\n      style=\"width: 100%\"\n      class=\"c-input\"\n      appearance=\"outline\"\n    >\n      <mat-select\n        (selectionChange)=\"changeProperty($event)\"\n        [value]=\"property.type\"\n        [required]=\"true\"\n        disableOptionCentering\n      >\n        <mat-select-trigger>\n          <ng-container *ngIf=\"!property.type\">\n            {{ 'label.none' | translate }}\n          </ng-container>\n          <ng-container *ngIf=\"property.type\">\n            <ng-container\n              *ngTemplateOutlet=\"option; context: {$implicit: property.type}\"\n            ></ng-container>\n          </ng-container>\n        </mat-select-trigger>\n        <mat-option [value]=\"null\" (click)=\"(property === null)\">\n          {{ 'label.none' | translate }}\n        </mat-option>\n        <mat-option *ngFor=\"let propertyType of selectablePropertyTypes\" [value]=\"propertyType\">\n          <ng-container\n            *ngTemplateOutlet=\"option; context: {$implicit: propertyType}\"\n          ></ng-container>\n        </mat-option>\n      </mat-select>\n      <mat-error>{{ 'label.required' | translate }}</mat-error>\n    </mat-form-field>\n\n    <ax-property-edit\n      *ngIf=\"form && form.value !== {}\"\n      [form]=\"form\"\n      [autofocus]=\"true\"\n    ></ax-property-edit>\n  </div>\n\n  <!--destination context-->\n  <div *ngIf=\"!saveOnAny\">\n    <div class=\"c-modal__section-title underline\">\n      {{ 'modal.missingProperty.context.title' | translate }}\n    </div>\n    <div class=\"list-row-wrapper\" *ngFor=\"let possibleContext of possibleContexts\">\n      <div\n        class=\"m-list-row\"\n        [class.is-selected]=\"possibleContext.selected\"\n        (click)=\"selectContext(possibleContext.context)\"\n      >\n        <ax-icon\n          class=\"icon c-settings__context-icon\"\n          [name]=\"iconNameForContextType(possibleContext.context.type)\"\n        ></ax-icon>\n\n        <div class=\"m-list-row__cell-middle\">\n          <span class=\"c-settings__context-label\">{{\n            possibleContext.context.id\n              ? (possibleContext.context | contextDisplayLabel)\n              : ('label.new' | translate: {word: possibleContext.context | contextDisplayLabel})\n          }}</span>\n        </div>\n        <div class=\"m-list-row__cell-last\">\n          <ax-icon *ngIf=\"possibleContext.selected\" class=\"icon green-text\" name=\"check\"></ax-icon>\n        </div>\n      </div>\n    </div>\n  </div>\n\n  <!--save-->\n  <div class=\"h-button-wrapper\">\n    <button\n      axButton\n      [axAutoDisableButton]=\"executeSaveAction()\"\n      [disabled]=\"form.invalid\"\n      class=\"cy-save\"\n      color=\"primary\"\n      filled\n    >\n      {{ 'label.save' | translate }}\n    </button>\n  </div>\n</div>\n", styles: [":host .h-button-wrapper{padding:1rem}.c-modal__section-title{padding-bottom:0}.list-row-wrapper{margin:0 1rem}.m-list-row{min-height:auto}.m-list-row .m-list-row__cell-middle{max-width:calc(100% - 20px)}.m-list-row .m-list-row__cell-last{display:flex}.property-edit{display:grid;grid-template-columns:7rem 1fr;grid-gap:1rem}.property-option{display:flex;align-items:center;color:#555}.property-option .icon{margin-right:.5rem}.property-option .icon{width:1rem;height:1rem}\n"] }]
        }], ctorParameters: () => [{ type: i1.ProfilesService }, { type: i1.ContextsService }, { type: i0.ChangeDetectorRef }, { type: i2.OverlayService }] });

class CreatePropertyModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: CreatePropertyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: CreatePropertyModule, declarations: [CreatePropertyComponent], imports: [CommonModule,
            IconsModule,
            PropertyEditModule,
            HelperPipesModule,
            SnackbarModule,
            ButtonModule,
            MatSelectModule,
            OverlayModule], exports: [CreatePropertyComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: CreatePropertyModule, imports: [CommonModule,
            IconsModule,
            PropertyEditModule,
            HelperPipesModule,
            SnackbarModule,
            ButtonModule,
            MatSelectModule,
            OverlayModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: CreatePropertyModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        CommonModule,
                        IconsModule,
                        PropertyEditModule,
                        HelperPipesModule,
                        SnackbarModule,
                        ButtonModule,
                        MatSelectModule,
                        OverlayModule,
                    ],
                    exports: [CreatePropertyComponent],
                    declarations: [CreatePropertyComponent],
                }]
        }] });

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

export { CreatePropertyComponent, CreatePropertyModule };
//# sourceMappingURL=aztrix-components-create-property.mjs.map
