import { Component, EventEmitter, Input, Output } from '@angular/core';
import { TenantLoginOptionsService, TenantService, UserService } from '@c8y/client';
import { clone } from 'lodash-es';
import { BsModalService } from 'ngx-bootstrap/modal';
import { AlertService } from '../alert/alert.service';
import { AppStateService } from '../common/ui-state.service';
import { TranslateService } from '../i18n/translate.service';
import { UserTotpSetupComponent } from './user-totp-setup.component';
import * as i0 from "@angular/core";
import * as i1 from "../common/ui-state.service";
import * as i2 from "../i18n/translate.service";
import * as i3 from "ngx-bootstrap/modal";
import * as i4 from "../alert/alert.service";
import * as i5 from "@c8y/client";
import * as i6 from "../forms/phone-validation.directive";
import * as i7 from "../forms/default-validation.directive";
import * as i8 from "@angular/forms";
import * as i9 from "../forms/form-group.component";
import * as i10 from "../forms/required-input-placeholder.directive";
import * as i11 from "../i18n/c8y-translate.directive";
import * as i12 from "@angular/common";
import * as i13 from "../authentication/new-password.component";
import * as i14 from "../i18n/c8y-translate.pipe";
export class UserEditComponent {
    set user(u) {
        if (u) {
            this._user = clone(u);
            this.userIsExternal = u.customProperties.userOrigin === 'OAUTH2';
            this.isPhoneRequired = this.isPhoneRequired && u.twoFactorAuthenticationEnabled;
        }
    }
    get user() {
        return this._user;
    }
    constructor(state, translate, bsModalService, alert, userService, tenantLoginOptionsService, tenantService) {
        this.state = state;
        this.translate = translate;
        this.bsModalService = bsModalService;
        this.alert = alert;
        this.userService = userService;
        this.tenantLoginOptionsService = tenantLoginOptionsService;
        this.tenantService = tenantService;
        this.loading = false;
        this.showProductExperienceOptions = false;
        this.isUsageTrackingEnabled = true;
        this.isUserEngagementPreferenceEnabled = true;
        this.onUser = new EventEmitter();
        this.onUsageTrackingChange = new EventEmitter();
        this.onUserEngagementPreferenceChange = new EventEmitter();
        this.onCancel = new EventEmitter();
        this.userHasActiveTotp = false;
        this.userCanSetupTotp = false;
        this.isPhoneRequired = false;
    }
    async ngOnInit() {
        const currentTenant = (await this.tenantService.current()).data;
        const { enabledOnSystemLevel, enabledOnTenantLevel } = await this.tenantService.getTfaSettings(currentTenant);
        this.isTfaEnabled = enabledOnSystemLevel || enabledOnTenantLevel;
        await this.initializeTotpSettings();
        if (this.user.twoFactorAuthenticationEnabled && !this.userCanSetupTotp) {
            this.isPhoneRequired = true;
        }
    }
    setupTotp() {
        this.bsModalService.show(UserTotpSetupComponent, {
            class: 'modal-sm',
            ariaDescribedby: 'modal-body',
            ariaLabelledBy: 'modal-title'
        });
        this.cancel(); // to close the user edit modal and prevent console errors on logout
    }
    cancel() {
        this.onCancel.emit();
    }
    async save() {
        if (this.loading) {
            return;
        }
        if (this.showProductExperienceOptions) {
            this.onUsageTrackingChange.emit(this.isUsageTrackingEnabled);
            /**
             * Emits a user engagement preference change event.
             * If usage tracking is disabled, it emits `false`. Otherwise, it emits the current state of the user engagement preference.
             */
            this.onUserEngagementPreferenceChange.emit(this.isUsageTrackingEnabled === false ? false : this.isUserEngagementPreferenceEnabled);
        }
        this.onUser.emit(this._user);
    }
    onNewPasswordChanged(newPassword) {
        this._user.password = newPassword.password;
    }
    async initializeTotpSettings() {
        try {
            this.userCanSetupTotp = await this.canUserSetupTotp();
            if (this.userCanSetupTotp) {
                const { data: totpActivity } = await this.userService.getActivityTotp();
                this.userHasActiveTotp = totpActivity.isActive;
            }
        }
        catch (ex) {
            this.alert.removeLastDanger();
        }
    }
    async canUserSetupTotp() {
        // we don't check for tenant options here due to permission restrictions on that end-point
        const loginOptions = (await this.tenantLoginOptionsService.listForCurrentTenant()).data;
        return loginOptions.some(({ tfaStrategy = '' }) => tfaStrategy.toLowerCase() === 'totp');
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: UserEditComponent, deps: [{ token: i1.AppStateService }, { token: i2.TranslateService }, { token: i3.BsModalService }, { token: i4.AlertService }, { token: i5.UserService }, { token: i5.TenantLoginOptionsService }, { token: i5.TenantService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: UserEditComponent, selector: "c8y-user-edit", inputs: { loading: "loading", user: "user", showProductExperienceOptions: "showProductExperienceOptions", isUsageTrackingEnabled: "isUsageTrackingEnabled", isUserEngagementPreferenceEnabled: "isUserEngagementPreferenceEnabled" }, outputs: { onUser: "onUser", onUsageTrackingChange: "onUsageTrackingChange", onUserEngagementPreferenceChange: "onUserEngagementPreferenceChange", onCancel: "onCancel" }, ngImport: i0, template: "<form #userForm=\"ngForm\" (ngSubmit)=\"userForm.form.valid && save()\">\n  <div class=\"d-block p-24 p-b-0\">\n    <div class=\"alert alert-warning\" role=\"alert\" *ngIf=\"userIsExternal\" translate>\n      Some of the user settings are not editable here because they are managed via your\n      authorization server.\n    </div>\n    <c8y-form-group>\n      <label translate for=\"userName\">Username</label>\n      <input\n        id=\"userName\"\n        class=\"form-control\"\n        [(ngModel)]=\"user.userName\"\n        name=\"userName\"\n        autocomplete=\"off\"\n        required\n        maxlength=\"254\"\n        placeholder=\"{{ 'e.g. joe.doe@example.com`LOCALIZE`' | translate }}\"\n        [disabled]=\"user.id\"\n        c8yDefaultValidation=\"user\"\n      />\n    </c8y-form-group>\n\n    <c8y-form-group>\n      <label translate for=\"displayName\">Login alias</label>\n      <input\n        id=\"displayName\"\n        class=\"form-control\"\n        [(ngModel)]=\"user.displayName\"\n        name=\"displayName\"\n        autocomplete=\"off\"\n        maxlength=\"254\"\n        placeholder=\"{{ 'e.g. joe.doe`LOCALIZE`' | translate }}\"\n        [disabled]=\"userIsExternal\"\n        c8yDefaultValidation=\"loginAlias\"\n      />\n    </c8y-form-group>\n\n    <c8y-form-group [hasWarning]=\"!user.email\">\n      <label translate for=\"userEmail\">Email</label>\n      <input\n        id=\"userEmail\"\n        class=\"form-control\"\n        type=\"email\"\n        name=\"email\"\n        [maxlength]=\"254\"\n        autocomplete=\"off\"\n        placeholder=\"{{ 'e.g. joe.doe@example.com`LOCALIZE`' | translate }}\"\n        [(ngModel)]=\"user.email\"\n        email\n        [required]=\"true\"\n        [disabled]=\"userIsExternal\"\n      />\n    </c8y-form-group>\n\n    <div class=\"row\">\n      <div class=\"col-sm-6\">\n        <c8y-form-group>\n          <label translate for=\"userFirstName\">First name</label>\n          <input\n            id=\"userFirstName\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            placeholder=\"{{ 'e.g. Joe`LOCALIZE`' | translate }}\"\n            maxlength=\"50\"\n            name=\"firstName\"\n            [(ngModel)]=\"user.firstName\"\n            [disabled]=\"userIsExternal\"\n          />\n        </c8y-form-group>\n      </div>\n      <div class=\"col-sm-6\">\n        <c8y-form-group>\n          <label translate for=\"userLastName\">Last name</label>\n          <input\n            id=\"userLastName\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            placeholder=\"{{ 'e.g. Doe`LOCALIZE`' | translate }}\"\n            maxlength=\"50\"\n            name=\"lastName\"\n            [(ngModel)]=\"user.lastName\"\n            [disabled]=\"userIsExternal\"\n          />\n        </c8y-form-group>\n      </div>\n    </div>\n\n    <c8y-form-group>\n      <label translate for=\"userTelephone\">Telephone</label>\n      <input\n        id=\"userTelephone\"\n        class=\"form-control\"\n        autocomplete=\"off\"\n        name=\"phone\"\n        maxlength=\"254\"\n        [(ngModel)]=\"user.phone\"\n        placeholder=\"{{ 'e.g. +49 9 876 543 210`LOCALIZE`' | translate }}\"\n        c8yPhoneValidation\n        [required]=\"isPhoneRequired\"\n        [disabled]=\"userIsExternal\"\n      />\n    </c8y-form-group>\n\n    <c8y-form-group class=\"p-t-16 separator-top\" *ngIf=\"showProductExperienceOptions\">\n      <label translate>Product experience</label>\n      <label class=\"c8y-switch\" for=\"productUsageTracking\">\n        <input\n          id=\"productUsageTracking\"\n          name=\"productUsageTracking\"\n          type=\"checkbox\"\n          [(ngModel)]=\"isUsageTrackingEnabled\"\n        />\n        <span></span>\n        {{ 'Enable personalized product experience tracking' | translate }}\n      </label>\n      <ng-container *ngIf=\"isUsageTrackingEnabled\">\n        <label class=\"c8y-switch m-l-0\" for=\"userEngagementPreference\">\n          <input\n            id=\"userEngagementPreference\"\n            name=\"userEngagementPreference\"\n            type=\"checkbox\"\n            [(ngModel)]=\"isUserEngagementPreferenceEnabled\"\n          />\n          <span></span>\n          {{ 'Enable in-product information & communication' | translate }}\n        </label>\n      </ng-container>\n    </c8y-form-group>\n\n    <div class=\"form-group p-t-16 separator-top\" *ngIf=\"!userIsExternal\">\n      <label class=\"control-label\">{{ 'Login options' | translate }}</label>\n      <c8y-new-password (password)=\"onNewPasswordChanged($event)\"></c8y-new-password>\n      <button\n        class=\"btn btn-default\"\n        type=\"button\"\n        title=\"{{ 'Set up two-factor authentication' | translate }}\"\n        (click)=\"setupTotp()\"\n        *ngIf=\"userCanSetupTotp && !userHasActiveTotp && isTfaEnabled\"\n      >\n        {{ 'Set up two-factor authentication' | translate }}\n      </button>\n    </div>\n\n    <c8y-form-group *ngIf=\"!!(state.state$ | async).newsletter\">\n      <label translate>Newsletter</label>\n      <label\n        title=\"{{ 'Send me information about outages, maintenance or updates.' | translate }}\"\n        class=\"c8y-checkbox\"\n      >\n        <input\n          type=\"checkbox\"\n          name=\"newsletter\"\n          [(ngModel)]=\"user.newsletter\"\n          [disabled]=\"userIsExternal\"\n        />\n        <span></span>\n        <span>\n          {{ 'Send me information about outages, maintenance or updates.' | translate }}\n        </span>\n      </label>\n    </c8y-form-group>\n  </div>\n  <div class=\"modal-footer separator-top bg-level-0 sticky-bottom\">\n    <button\n      class=\"btn btn-default\"\n      type=\"button\"\n      title=\"{{ 'Cancel' | translate }}\"\n      (click)=\"cancel()\"\n    >\n      {{ 'Cancel' | translate }}\n    </button>\n    <button\n      class=\"btn btn-primary\"\n      type=\"submit\"\n      title=\"{{ 'Save' | translate }}\"\n      [disabled]=\"!userForm.form.valid || userForm.form.pristine || loading\"\n    >\n      {{ 'Save' | translate }}\n    </button>\n  </div>\n</form>\n", dependencies: [{ kind: "directive", type: i6.PhoneValidationDirective, selector: "[c8yPhoneValidation]" }, { kind: "directive", type: i7.DefaultValidationDirective, selector: "[c8yDefaultValidation]", inputs: ["c8yDefaultValidation"] }, { kind: "directive", type: i8.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i8.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i8.CheckboxControlValueAccessor, selector: "input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]" }, { kind: "directive", type: i8.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i8.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i8.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i8.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "directive", type: i8.EmailValidator, selector: "[email][formControlName],[email][formControl],[email][ngModel]", inputs: ["email"] }, { kind: "directive", type: i8.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i8.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "component", type: i9.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i10.RequiredInputPlaceholderDirective, selector: "input[required], input[formControlName]" }, { kind: "directive", type: i11.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i12.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i13.NewPasswordComponent, selector: "c8y-new-password", inputs: ["showChangePasswordButton", "requireStrongPassword"], outputs: ["password"] }, { kind: "pipe", type: i14.C8yTranslatePipe, name: "translate" }, { kind: "pipe", type: i12.AsyncPipe, name: "async" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: UserEditComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-user-edit', template: "<form #userForm=\"ngForm\" (ngSubmit)=\"userForm.form.valid && save()\">\n  <div class=\"d-block p-24 p-b-0\">\n    <div class=\"alert alert-warning\" role=\"alert\" *ngIf=\"userIsExternal\" translate>\n      Some of the user settings are not editable here because they are managed via your\n      authorization server.\n    </div>\n    <c8y-form-group>\n      <label translate for=\"userName\">Username</label>\n      <input\n        id=\"userName\"\n        class=\"form-control\"\n        [(ngModel)]=\"user.userName\"\n        name=\"userName\"\n        autocomplete=\"off\"\n        required\n        maxlength=\"254\"\n        placeholder=\"{{ 'e.g. joe.doe@example.com`LOCALIZE`' | translate }}\"\n        [disabled]=\"user.id\"\n        c8yDefaultValidation=\"user\"\n      />\n    </c8y-form-group>\n\n    <c8y-form-group>\n      <label translate for=\"displayName\">Login alias</label>\n      <input\n        id=\"displayName\"\n        class=\"form-control\"\n        [(ngModel)]=\"user.displayName\"\n        name=\"displayName\"\n        autocomplete=\"off\"\n        maxlength=\"254\"\n        placeholder=\"{{ 'e.g. joe.doe`LOCALIZE`' | translate }}\"\n        [disabled]=\"userIsExternal\"\n        c8yDefaultValidation=\"loginAlias\"\n      />\n    </c8y-form-group>\n\n    <c8y-form-group [hasWarning]=\"!user.email\">\n      <label translate for=\"userEmail\">Email</label>\n      <input\n        id=\"userEmail\"\n        class=\"form-control\"\n        type=\"email\"\n        name=\"email\"\n        [maxlength]=\"254\"\n        autocomplete=\"off\"\n        placeholder=\"{{ 'e.g. joe.doe@example.com`LOCALIZE`' | translate }}\"\n        [(ngModel)]=\"user.email\"\n        email\n        [required]=\"true\"\n        [disabled]=\"userIsExternal\"\n      />\n    </c8y-form-group>\n\n    <div class=\"row\">\n      <div class=\"col-sm-6\">\n        <c8y-form-group>\n          <label translate for=\"userFirstName\">First name</label>\n          <input\n            id=\"userFirstName\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            placeholder=\"{{ 'e.g. Joe`LOCALIZE`' | translate }}\"\n            maxlength=\"50\"\n            name=\"firstName\"\n            [(ngModel)]=\"user.firstName\"\n            [disabled]=\"userIsExternal\"\n          />\n        </c8y-form-group>\n      </div>\n      <div class=\"col-sm-6\">\n        <c8y-form-group>\n          <label translate for=\"userLastName\">Last name</label>\n          <input\n            id=\"userLastName\"\n            class=\"form-control\"\n            autocomplete=\"off\"\n            placeholder=\"{{ 'e.g. Doe`LOCALIZE`' | translate }}\"\n            maxlength=\"50\"\n            name=\"lastName\"\n            [(ngModel)]=\"user.lastName\"\n            [disabled]=\"userIsExternal\"\n          />\n        </c8y-form-group>\n      </div>\n    </div>\n\n    <c8y-form-group>\n      <label translate for=\"userTelephone\">Telephone</label>\n      <input\n        id=\"userTelephone\"\n        class=\"form-control\"\n        autocomplete=\"off\"\n        name=\"phone\"\n        maxlength=\"254\"\n        [(ngModel)]=\"user.phone\"\n        placeholder=\"{{ 'e.g. +49 9 876 543 210`LOCALIZE`' | translate }}\"\n        c8yPhoneValidation\n        [required]=\"isPhoneRequired\"\n        [disabled]=\"userIsExternal\"\n      />\n    </c8y-form-group>\n\n    <c8y-form-group class=\"p-t-16 separator-top\" *ngIf=\"showProductExperienceOptions\">\n      <label translate>Product experience</label>\n      <label class=\"c8y-switch\" for=\"productUsageTracking\">\n        <input\n          id=\"productUsageTracking\"\n          name=\"productUsageTracking\"\n          type=\"checkbox\"\n          [(ngModel)]=\"isUsageTrackingEnabled\"\n        />\n        <span></span>\n        {{ 'Enable personalized product experience tracking' | translate }}\n      </label>\n      <ng-container *ngIf=\"isUsageTrackingEnabled\">\n        <label class=\"c8y-switch m-l-0\" for=\"userEngagementPreference\">\n          <input\n            id=\"userEngagementPreference\"\n            name=\"userEngagementPreference\"\n            type=\"checkbox\"\n            [(ngModel)]=\"isUserEngagementPreferenceEnabled\"\n          />\n          <span></span>\n          {{ 'Enable in-product information & communication' | translate }}\n        </label>\n      </ng-container>\n    </c8y-form-group>\n\n    <div class=\"form-group p-t-16 separator-top\" *ngIf=\"!userIsExternal\">\n      <label class=\"control-label\">{{ 'Login options' | translate }}</label>\n      <c8y-new-password (password)=\"onNewPasswordChanged($event)\"></c8y-new-password>\n      <button\n        class=\"btn btn-default\"\n        type=\"button\"\n        title=\"{{ 'Set up two-factor authentication' | translate }}\"\n        (click)=\"setupTotp()\"\n        *ngIf=\"userCanSetupTotp && !userHasActiveTotp && isTfaEnabled\"\n      >\n        {{ 'Set up two-factor authentication' | translate }}\n      </button>\n    </div>\n\n    <c8y-form-group *ngIf=\"!!(state.state$ | async).newsletter\">\n      <label translate>Newsletter</label>\n      <label\n        title=\"{{ 'Send me information about outages, maintenance or updates.' | translate }}\"\n        class=\"c8y-checkbox\"\n      >\n        <input\n          type=\"checkbox\"\n          name=\"newsletter\"\n          [(ngModel)]=\"user.newsletter\"\n          [disabled]=\"userIsExternal\"\n        />\n        <span></span>\n        <span>\n          {{ 'Send me information about outages, maintenance or updates.' | translate }}\n        </span>\n      </label>\n    </c8y-form-group>\n  </div>\n  <div class=\"modal-footer separator-top bg-level-0 sticky-bottom\">\n    <button\n      class=\"btn btn-default\"\n      type=\"button\"\n      title=\"{{ 'Cancel' | translate }}\"\n      (click)=\"cancel()\"\n    >\n      {{ 'Cancel' | translate }}\n    </button>\n    <button\n      class=\"btn btn-primary\"\n      type=\"submit\"\n      title=\"{{ 'Save' | translate }}\"\n      [disabled]=\"!userForm.form.valid || userForm.form.pristine || loading\"\n    >\n      {{ 'Save' | translate }}\n    </button>\n  </div>\n</form>\n" }]
        }], ctorParameters: () => [{ type: i1.AppStateService }, { type: i2.TranslateService }, { type: i3.BsModalService }, { type: i4.AlertService }, { type: i5.UserService }, { type: i5.TenantLoginOptionsService }, { type: i5.TenantService }], propDecorators: { loading: [{
                type: Input
            }], user: [{
                type: Input
            }], showProductExperienceOptions: [{
                type: Input
            }], isUsageTrackingEnabled: [{
                type: Input
            }], isUserEngagementPreferenceEnabled: [{
                type: Input
            }], onUser: [{
                type: Output
            }], onUsageTrackingChange: [{
                type: Output
            }], onUserEngagementPreferenceChange: [{
                type: Output
            }], onCancel: [{
                type: Output
            }] } });
//# sourceMappingURL=data:application/json;base64, 