import { __awaiter } from "tslib";
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { UserService, TenantLoginOptionsService, TenantService } from '@c8y/client';
import { clone } from 'lodash-es';
import { AppStateService } from '../common/ui-state.service';
import { TranslateService } from '../i18n/translate.service';
import { BsModalService } from 'ngx-bootstrap/modal';
import { PasswordService } from '../authentication/password.service';
import { UserTotpSetupComponent } from './user-totp-setup.component';
import { AlertService } from '../alert/alert.service';
import { ModalService } from '../modal/modal.service';
import { UserPreferencesService } from '../common/user-preferences/user-preferences.service';
export class UserEditComponent {
    constructor(state, translate, passwordService, modalConfirmService, bsModalService, alert, userService, tenantLoginOptionsService, tenantService, userPreferencesService) {
        this.state = state;
        this.translate = translate;
        this.passwordService = passwordService;
        this.modalConfirmService = modalConfirmService;
        this.bsModalService = bsModalService;
        this.alert = alert;
        this.userService = userService;
        this.tenantLoginOptionsService = tenantLoginOptionsService;
        this.tenantService = tenantService;
        this.userPreferencesService = userPreferencesService;
        this.loading = false;
        this.showProductUsageSetting = false;
        this.isUsageTrackingEnabled = true;
        this.onUser = new EventEmitter();
        this.onLanguage = new EventEmitter();
        this.onProductExperience = new EventEmitter();
        this.onCancel = new EventEmitter();
        this.userHasActiveTotp = false;
        this.userCanSetupTotp = false;
        this.isPhoneRequired = false;
    }
    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;
    }
    ngOnInit() {
        return __awaiter(this, void 0, void 0, function* () {
            const currentTenant = (yield this.tenantService.current()).data;
            const { enabledOnSystemLevel, enabledOnTenantLevel } = yield this.tenantService.getTfaSettings(currentTenant);
            this.isTfaEnabled = enabledOnSystemLevel || enabledOnTenantLevel;
            yield this.initializeTotpSettings();
            if (this.user.twoFactorAuthenticationEnabled && !this.userCanSetupTotp) {
                this.isPhoneRequired = true;
            }
        });
    }
    get langs() {
        return this.state.state.langs;
    }
    setupTotp() {
        this.bsModalService.show(UserTotpSetupComponent, { class: 'modal-sm' });
        this.cancel(); // to close the user edit modal and prevent console errors on logout
    }
    cancel() {
        this.onCancel.emit();
    }
    save() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.loading) {
                return;
            }
            if (this.showProductUsageSetting) {
                this.onProductExperience.emit(this.isUsageTrackingEnabled);
                this.userPreferencesService.set('gainsightEnabled', this.isUsageTrackingEnabled);
            }
            this._user.password ? this.saveAfterPasswordConfirmation() : this.onUser.emit(this._user);
        });
    }
    onNewPasswordChanged(newPassword) {
        this._user.password = newPassword.password;
    }
    initializeTotpSettings() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                this.userCanSetupTotp = yield this.canUserSetupTotp();
                if (this.userCanSetupTotp) {
                    const { data: totpActivity } = yield this.userService.getActivityTotp();
                    this.userHasActiveTotp = totpActivity.isActive;
                }
            }
            catch (ex) {
                this.alert.removeLastDanger();
            }
        });
    }
    canUserSetupTotp() {
        return __awaiter(this, void 0, void 0, function* () {
            // we don't check for tenant options here due to permission restrictions on that end-point
            const loginOptions = (yield this.tenantLoginOptionsService.listForCurrentTenant()).data;
            return loginOptions.some(({ tfaStrategy = '' }) => tfaStrategy.toLowerCase() === 'totp');
        });
    }
    saveAfterPasswordConfirmation() {
        this.passwordService.confirmPassword().subscribe(confirmed => {
            if (confirmed) {
                this.onUser.emit(this._user);
            }
        });
    }
}
UserEditComponent.decorators = [
    { type: Component, args: [{
                selector: 'c8y-user-edit',
                template: "<form #userForm=\"ngForm\" (ngSubmit)=\"userForm.form.valid && save()\">\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 authorization\n    server.\n  </div>\n  <c8y-form-group>\n    <label translate for=\"userName\">Username (e.g. email)</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\" style=\"margin-left:-15px; margin-right:-15px\">\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          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          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      c8yDefaultValidation=\"phoneNumber\"\n      [required]=\"isPhoneRequired\"\n      [disabled]=\"userIsExternal\"\n    />\n  </c8y-form-group>\n\n  <c8y-form-group>\n    <label translate for=\"userLang\">Language</label>\n    <div class=\"c8y-select-wrapper\">\n      <select\n        id=\"userLang\"\n        class=\"form-control\"\n        #selectLang\n        name=\"lang\"\n        [(ngModel)]=\"lang\"\n        (change)=\"onLanguage.emit(selectLang.value)\"\n      >\n        <option *ngFor=\"let lang of langs\" [value]=\"lang\">{{\n          translate.getNativeLanguage(lang)\n        }}</option>\n      </select>\n      <span></span>\n    </div>\n  </c8y-form-group>\n\n  <c8y-form-group class=\"p-t-8 p-b-8 separator-top\" *ngIf=\"showProductUsageSetting\">\n    <strong translate>Product experience</strong>\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 anonymous tracking to enhance the product experience' | translate }}\n    </label>\n  </c8y-form-group>\n\n  <div class=\"form-group\" *ngIf=\"!userIsExternal\">\n    <label class=\"control-label\">{{ 'Login options' | translate }}</label>\n    <c8y-new-password (password)=\"onNewPasswordChanged($event)\"></c8y-new-password>\n    <button\n      title=\"{{ 'Set up two-factor authentication' | translate }}\"\n      class=\"btn btn-default\"\n      type=\"button\"\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\n  <div class=\"modal-footer\">\n    <button\n      title=\"{{ 'Cancel' | translate }}\"\n      class=\"btn btn-default\"\n      type=\"button\"\n      (click)=\"cancel()\"\n    >\n      {{ 'Cancel' | translate }}\n    </button>\n    <button\n      title=\"{{ 'Save' | translate }}\"\n      class=\"btn btn-primary\"\n      type=\"submit\"\n      [disabled]=\"!userForm.form.valid || userForm.form.pristine || loading\"\n    >\n      {{ 'Save' | translate }}\n    </button>\n  </div>\n</form>\n"
            },] }
];
UserEditComponent.ctorParameters = () => [
    { type: AppStateService },
    { type: TranslateService },
    { type: PasswordService },
    { type: ModalService },
    { type: BsModalService },
    { type: AlertService },
    { type: UserService },
    { type: TenantLoginOptionsService },
    { type: TenantService },
    { type: UserPreferencesService }
];
UserEditComponent.propDecorators = {
    lang: [{ type: Input }],
    loading: [{ type: Input }],
    user: [{ type: Input }],
    showProductUsageSetting: [{ type: Input }],
    isUsageTrackingEnabled: [{ type: Input }],
    onUser: [{ type: Output }],
    onLanguage: [{ type: Output }],
    onProductExperience: [{ type: Output }],
    onCancel: [{ type: Output }]
};
//# sourceMappingURL=data:application/json;base64, 