import { Component, Input } from '@angular/core';
import { TenantLoginOptionType } from '@c8y/client';
import { ControlContainer, NgForm } from '@angular/forms';
import { defaults, cloneDeep, isFinite } from 'lodash-es';
import { gettext, TenantUiService } from '@c8y/ngx-components';
import { TranslateService } from '@ngx-translate/core';
import { isOauthInternal } from './basic-settings.model';
import * as i0 from "@angular/core";
import * as i1 from "@c8y/ngx-components";
import * as i2 from "@ngx-translate/core";
import * as i3 from "@angular/common";
import * as i4 from "@angular/forms";
import * as i5 from "ngx-bootstrap/popover";
export class SessionConfigurationComponent {
    constructor(tenantUiService, translateService) {
        this.tenantUiService = tenantUiService;
        this.translateService = translateService;
        this.tenantLoginOptionTypeEnum = TenantLoginOptionType;
        this.ABSOLUTE_TIMEOUT_VALIDATION_MESSAGE = gettext('The value must be greater than "Token lifespan" and not less than {{ minAbsoluteTimeout }}.');
        this.RENEWAL_TIMEOUT_VALIDATION_MESSAGE = gettext('The value must be less than "Token lifespan".');
        this.MAX_TOKEN_LIFESPAN_VALIDATION_MESSAGE = gettext('The value must be less than "Session absolute timeout".');
        this.MIN_TOKEN_LIFESPAN_VALIDATION_MESSAGE = gettext('The value must be greater than "Session renewal timeout".');
        this.USER_AGENT_VALIDATION_REQUIRED_POPOVER = gettext('If selected, then every request needs to use the same "User-Agent" header as the first request which initiated the session.');
        this.MIN_ABSOLUTE_TIMEOUT = 15 * 60;
        this.ABSOLUTE_TIMEOUT_VALIDATION_MESSAGE = this.translateService.instant(this.ABSOLUTE_TIMEOUT_VALIDATION_MESSAGE, { minAbsoluteTimeout: this.MIN_ABSOLUTE_TIMEOUT });
    }
    ngOnChanges(changes) {
        if (changes.authConfiguration && changes.authConfiguration.currentValue) {
            const oauthInternal = changes.authConfiguration.currentValue.loginOptions.find(isOauthInternal) || {};
            this.originalSessionConfiguration = cloneDeep(oauthInternal.sessionConfiguration);
            this.sessionConfiguration = oauthInternal.sessionConfiguration;
            this.previousTokenLifespan =
                this.authConfiguration.tenantOptions['oauth.internal']['basic-token.lifespan.seconds'];
        }
    }
    get renewalTimeoutSeconds() {
        const sessionConfiguration = this.sessionConfiguration;
        return this.convertToSeconds(sessionConfiguration.renewalTimeoutMillis);
    }
    set renewalTimeoutSeconds(value) {
        this.sessionConfiguration.renewalTimeoutMillis = this.convertToMillis(value);
    }
    get absoluteTimeoutSeconds() {
        const sessionConfiguration = this.sessionConfiguration;
        return this.convertToSeconds(sessionConfiguration.absoluteTimeoutMillis);
    }
    set absoluteTimeoutSeconds(value) {
        this.sessionConfiguration.absoluteTimeoutMillis = this.convertToMillis(value);
    }
    get maximumNumberOfParallelSessions() {
        return this.sessionConfiguration.maximumNumberOfParallelSessions;
    }
    set maximumNumberOfParallelSessions(value) {
        this.sessionConfiguration.maximumNumberOfParallelSessions = value;
    }
    get userAgentValidationRequired() {
        return this.sessionConfiguration.userAgentValidationRequired;
    }
    set userAgentValidationRequired(value) {
        this.sessionConfiguration.userAgentValidationRequired = value;
    }
    get basicTokenLifespan() {
        return this.authConfiguration.tenantOptions['oauth.internal']['basic-token.lifespan.seconds'];
    }
    set basicTokenLifespan(value) {
        this.authConfiguration.tenantOptions['oauth.internal']['basic-token.lifespan.seconds'] = value;
    }
    get useSessionConfiguration() {
        return !!this.sessionConfiguration;
    }
    set useSessionConfiguration(value) {
        this.sessionConfiguration = value
            ? defaults({}, this.originalSessionConfiguration, {
                absoluteTimeoutMillis: 1209600000, // 14 days
                renewalTimeoutMillis: 86400000, // 1 day
                maximumNumberOfParallelSessions: 5,
                userAgentValidationRequired: false
            })
            : null;
        this.basicTokenLifespan = this.previousTokenLifespan || 172800; // 2 days
    }
    get absoluteTimeoutConstraints() {
        return {
            min: Math.max(this.MIN_ABSOLUTE_TIMEOUT, this.basicTokenLifespan + 1)
        };
    }
    get renewalTimeoutConstraints() {
        return {
            min: this.MIN_ABSOLUTE_TIMEOUT / 2,
            max: this.basicTokenLifespan ? this.basicTokenLifespan - 1 : null
        };
    }
    get basicTokenLifespanConstraints() {
        return {
            min: this.renewalTimeoutSeconds ? this.renewalTimeoutSeconds + 1 : null,
            max: this.absoluteTimeoutSeconds ? this.absoluteTimeoutSeconds - 1 : null
        };
    }
    get sessionConfiguration() {
        return this.authConfiguration.loginOptions.find(isOauthInternal).sessionConfiguration;
    }
    set sessionConfiguration(value) {
        this.authConfiguration.loginOptions.find(isOauthInternal).sessionConfiguration = value;
    }
    convertToMillis(seconds) {
        return isFinite(seconds) ? seconds * 1000 : null;
    }
    convertToSeconds(milliseconds) {
        return isFinite(milliseconds) ? Math.ceil(milliseconds / 1000) : null;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: SessionConfigurationComponent, deps: [{ token: i1.TenantUiService }, { token: i2.TranslateService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: SessionConfigurationComponent, selector: "c8y-session-configuration", inputs: { authConfiguration: "authConfiguration" }, usesOnChanges: true, ngImport: i0, template: "<div\n  class=\"card-block separator-top overflow-auto\"\n  *ngIf=\"authConfiguration.preferredLoginOptionType === tenantLoginOptionTypeEnum.OAUTH2_INTERNAL\"\n>\n  <div class=\"col-sm-2\">\n    <div class=\"h4 text-normal text-right text-left-xs\">\n      {{ 'OAI-Secure session configuration' | translate }}\n    </div>\n  </div>\n\n  <div class=\"col-sm-9\">\n    <div class=\"row\">\n      <div class=\"col-sm-6\">\n        <c8y-form-group>\n          <label class=\"c8y-switch\" title=\"{{ 'Use session configuration' | translate }}\">\n            <input\n              type=\"checkbox\"\n              name=\"useSessionConfiguration\"\n              [(ngModel)]=\"useSessionConfiguration\"\n            />\n            <span></span>\n            <span>{{ 'Use session configuration' | translate }}</span>\n          </label>\n        </c8y-form-group>\n      </div>\n    </div>\n\n    <fieldset *ngIf=\"sessionConfiguration\">\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label class=\"c8y-switch\" title=\"{{ 'User agent validation required' | translate }}\">\n              <input\n                type=\"checkbox\"\n                name=\"userAgentValidationRequired\"\n                [(ngModel)]=\"userAgentValidationRequired\"\n              />\n              <span></span>\n              <span>{{ 'User agent validation required' | translate }}</span>\n              <button\n                class=\"btn-help btn-help--sm\"\n                type=\"button\"\n                [attr.aria-label]=\"'Help' | translate\"\n                popover=\"{{ USER_AGENT_VALIDATION_REQUIRED_POPOVER | translate }}\"\n                placement=\"right\"\n                triggers=\"focus\"\n                container=\"body\"\n              ></button>\n            </label>\n          </c8y-form-group>\n        </div>\n      </div>\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Session absolute timeout' | translate }}\">\n              {{ 'Session absolute timeout' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"absoluteTimeoutSeconds\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"absoluteTimeoutSeconds\"\n                [required]=\"useSessionConfiguration\"\n                [min]=\"absoluteTimeoutConstraints.min\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>seconds</span>\n            </div>\n            <c8y-messages>\n              <c8y-message\n                name=\"min\"\n                text=\"{{ ABSOLUTE_TIMEOUT_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Session renewal timeout' | translate }}\">\n              {{ 'Session renewal timeout' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"renewalTimeoutSeconds\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"renewalTimeoutSeconds\"\n                [required]=\"useSessionConfiguration\"\n                [max]=\"renewalTimeoutConstraints.max\"\n                [min]=\"renewalTimeoutConstraints.min\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>seconds</span>\n            </div>\n            <c8y-messages>\n              <c8y-message\n                name=\"max\"\n                text=\"{{ RENEWAL_TIMEOUT_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n      </div>\n\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Maximum parallel sessions per user' | translate }}\">\n              {{ 'Maximum parallel sessions per user' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"maximumNumberOfParallelSessions\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"maximumNumberOfParallelSessions\"\n                [required]=\"useSessionConfiguration\"\n                [min]=\"1\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>sessions</span>\n            </div>\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Token lifespan' | translate }}\">\n              {{ 'Token lifespan' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"basicTokenLifespan\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"basicTokenLifespan\"\n                [required]=\"useSessionConfiguration\"\n                [max]=\"basicTokenLifespanConstraints.max\"\n                [min]=\"basicTokenLifespanConstraints.min\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>seconds</span>\n            </div>\n            <c8y-messages>\n              <c8y-message\n                name=\"max\"\n                text=\"{{ MAX_TOKEN_LIFESPAN_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n              <c8y-message\n                name=\"min\"\n                text=\"{{ MIN_TOKEN_LIFESPAN_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n      </div>\n    </fieldset>\n  </div>\n</div>\n", dependencies: [{ kind: "directive", type: i1.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.MinValidationDirective, selector: "[min]", inputs: ["min"] }, { kind: "directive", type: i1.MaxValidationDirective, selector: "[max]", inputs: ["max"] }, { kind: "directive", type: i4.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: i4.NumberValueAccessor, selector: "input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]" }, { kind: "directive", type: i4.CheckboxControlValueAccessor, selector: "input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]" }, { kind: "directive", type: i4.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i4.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i4.MinValidator, selector: "input[type=number][min][formControlName],input[type=number][min][formControl],input[type=number][min][ngModel]", inputs: ["min"] }, { kind: "directive", type: i4.MaxValidator, selector: "input[type=number][max][formControlName],input[type=number][max][formControl],input[type=number][max][ngModel]", inputs: ["max"] }, { kind: "directive", type: i4.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "component", type: i1.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i1.MessageDirective, selector: "c8y-message", inputs: ["name", "text"] }, { kind: "component", type: i1.MessagesComponent, selector: "c8y-messages", inputs: ["show", "defaults", "helpMessage"] }, { kind: "directive", type: i1.RequiredInputPlaceholderDirective, selector: "input[required], input[formControlName]" }, { kind: "directive", type: i5.PopoverDirective, selector: "[popover]", inputs: ["adaptivePosition", "boundariesElement", "popover", "popoverContext", "popoverTitle", "placement", "outsideClick", "triggers", "container", "containerClass", "isOpen", "delay"], outputs: ["onShown", "onHidden"], exportAs: ["bs-popover"] }, { kind: "pipe", type: i1.C8yTranslatePipe, name: "translate" }], viewProviders: [{ provide: ControlContainer, useExisting: NgForm }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: SessionConfigurationComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-session-configuration', viewProviders: [{ provide: ControlContainer, useExisting: NgForm }], template: "<div\n  class=\"card-block separator-top overflow-auto\"\n  *ngIf=\"authConfiguration.preferredLoginOptionType === tenantLoginOptionTypeEnum.OAUTH2_INTERNAL\"\n>\n  <div class=\"col-sm-2\">\n    <div class=\"h4 text-normal text-right text-left-xs\">\n      {{ 'OAI-Secure session configuration' | translate }}\n    </div>\n  </div>\n\n  <div class=\"col-sm-9\">\n    <div class=\"row\">\n      <div class=\"col-sm-6\">\n        <c8y-form-group>\n          <label class=\"c8y-switch\" title=\"{{ 'Use session configuration' | translate }}\">\n            <input\n              type=\"checkbox\"\n              name=\"useSessionConfiguration\"\n              [(ngModel)]=\"useSessionConfiguration\"\n            />\n            <span></span>\n            <span>{{ 'Use session configuration' | translate }}</span>\n          </label>\n        </c8y-form-group>\n      </div>\n    </div>\n\n    <fieldset *ngIf=\"sessionConfiguration\">\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label class=\"c8y-switch\" title=\"{{ 'User agent validation required' | translate }}\">\n              <input\n                type=\"checkbox\"\n                name=\"userAgentValidationRequired\"\n                [(ngModel)]=\"userAgentValidationRequired\"\n              />\n              <span></span>\n              <span>{{ 'User agent validation required' | translate }}</span>\n              <button\n                class=\"btn-help btn-help--sm\"\n                type=\"button\"\n                [attr.aria-label]=\"'Help' | translate\"\n                popover=\"{{ USER_AGENT_VALIDATION_REQUIRED_POPOVER | translate }}\"\n                placement=\"right\"\n                triggers=\"focus\"\n                container=\"body\"\n              ></button>\n            </label>\n          </c8y-form-group>\n        </div>\n      </div>\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Session absolute timeout' | translate }}\">\n              {{ 'Session absolute timeout' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"absoluteTimeoutSeconds\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"absoluteTimeoutSeconds\"\n                [required]=\"useSessionConfiguration\"\n                [min]=\"absoluteTimeoutConstraints.min\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>seconds</span>\n            </div>\n            <c8y-messages>\n              <c8y-message\n                name=\"min\"\n                text=\"{{ ABSOLUTE_TIMEOUT_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Session renewal timeout' | translate }}\">\n              {{ 'Session renewal timeout' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"renewalTimeoutSeconds\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"renewalTimeoutSeconds\"\n                [required]=\"useSessionConfiguration\"\n                [max]=\"renewalTimeoutConstraints.max\"\n                [min]=\"renewalTimeoutConstraints.min\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>seconds</span>\n            </div>\n            <c8y-messages>\n              <c8y-message\n                name=\"max\"\n                text=\"{{ RENEWAL_TIMEOUT_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n      </div>\n\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Maximum parallel sessions per user' | translate }}\">\n              {{ 'Maximum parallel sessions per user' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"maximumNumberOfParallelSessions\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"maximumNumberOfParallelSessions\"\n                [required]=\"useSessionConfiguration\"\n                [min]=\"1\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>sessions</span>\n            </div>\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-6\">\n          <c8y-form-group>\n            <label title=\"{{ 'Token lifespan' | translate }}\">\n              {{ 'Token lifespan' | translate }}\n            </label>\n            <div class=\"input-group\">\n              <input\n                type=\"number\"\n                name=\"basicTokenLifespan\"\n                class=\"form-control text-right\"\n                [(ngModel)]=\"basicTokenLifespan\"\n                [required]=\"useSessionConfiguration\"\n                [max]=\"basicTokenLifespanConstraints.max\"\n                [min]=\"basicTokenLifespanConstraints.min\"\n                step=\"1\"\n              />\n              <span class=\"input-group-addon\" translate>seconds</span>\n            </div>\n            <c8y-messages>\n              <c8y-message\n                name=\"max\"\n                text=\"{{ MAX_TOKEN_LIFESPAN_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n              <c8y-message\n                name=\"min\"\n                text=\"{{ MIN_TOKEN_LIFESPAN_VALIDATION_MESSAGE | translate }}\"\n              ></c8y-message>\n            </c8y-messages>\n          </c8y-form-group>\n        </div>\n      </div>\n    </fieldset>\n  </div>\n</div>\n" }]
        }], ctorParameters: () => [{ type: i1.TenantUiService }, { type: i2.TranslateService }], propDecorators: { authConfiguration: [{
                type: Input
            }] } });
//# sourceMappingURL=data:application/json;base64, 