import { Component, Output, EventEmitter } from '@angular/core';
import { LoginViews } from './login.model';
import { FetchClient } from '@c8y/client';
import { AppStateService } from '../common/ui-state.service';
import { LoginService } from './login.service';
import { AlertService } from '../alert/alert.service';
import { TranslateService } from '@ngx-translate/core';
import { gettext } from '../i18n/gettext';
import * as i0 from "@angular/core";
import * as i1 from "@c8y/client";
import * as i2 from "../common/ui-state.service";
import * as i3 from "./login.service";
import * as i4 from "../alert/alert.service";
import * as i5 from "@ngx-translate/core";
import * as i6 from "@angular/forms";
import * as i7 from "../i18n/c8y-translate.directive";
import * as i8 from "../forms/form-group.component";
import * as i9 from "../forms/required-input-placeholder.directive";
import * as i10 from "../i18n/c8y-translate.pipe";
/**
 * `TenantIdSetupComponent` is intended to be shown when tenant's id cannot be determined based on the current URL.
 * It asks the user to provide target tenant's id and then it fetches login options for this tenant.
 * In case of OAI-Secure login mode, login options will contain `domain` property set by backend.
 * The component will redirect user to this domain, preserving URL path and params.
 */
export class TenantIdSetupComponent {
    constructor(client, ui, loginService, alert, translateService) {
        this.client = client;
        this.ui = ui;
        this.loginService = loginService;
        this.alert = alert;
        this.translateService = translateService;
        this.onChangeView = new EventEmitter();
        this.LOGIN_VIEWS = LoginViews;
        this.model = {
            tenant: ''
        };
    }
    /**
     * Sets up login mode for particular tenant. In case of OAI-Secure will redirect user to tenant domain.
     */
    async setupLoginMode() {
        this.client.tenant = this.model.tenant;
        try {
            await this.ui.refreshLoginOptions();
            this.loginService.initLoginOptions();
            this.redirectToCorrectDomain();
        }
        catch (e) {
            if (e.res && e.res.status === 401) {
                this.alert.danger(this.translateService.instant(gettext('Could not find tenant with ID "{{ tenantId }}".'), { tenantId: this.model.tenant }));
            }
            else {
                this.alert.addServerFailure(e);
            }
        }
    }
    /**
     * Redirects to tenant domain when login mode contains domain.
     */
    redirectToCorrectDomain() {
        const loginRedirectDomain = this.loginService.loginMode.loginRedirectDomain;
        if (loginRedirectDomain) {
            const alreadyOnCorrectDomain = window.location.href.includes(loginRedirectDomain);
            if (!alreadyOnCorrectDomain) {
                this.loginService.redirectToDomain(loginRedirectDomain);
            }
            else {
                this.onChangeView.emit({
                    view: LoginViews.Credentials,
                    loginViewParams: { showTenant: true, disableTenant: true }
                });
            }
        }
        else {
            this.onChangeView.emit({ view: LoginViews.Credentials });
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: TenantIdSetupComponent, deps: [{ token: i1.FetchClient }, { token: i2.AppStateService }, { token: i3.LoginService }, { token: i4.AlertService }, { token: i5.TranslateService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.9", type: TenantIdSetupComponent, selector: "c8y-tenant-id-setup", outputs: { onChangeView: "onChangeView" }, ngImport: i0, template: "<form #tenantIdSetupForm=\"ngForm\" class=\"loginForm\" (ngSubmit)=\"setupLoginMode()\" novalidate>\n  <div class=\"legend form-block center\" translate>Tenant setup</div>\n  <c8y-form-group class=\"tenantField\" id=\"tenantField\">\n    <label for=\"tenant\" translate>Tenant ID</label>\n    <input\n      [(ngModel)]=\"model.tenant\"\n      #tenant=\"ngModel\"\n      type=\"text\"\n      name=\"tenant\"\n      id=\"tenant\"\n      autocapitalize=\"off\"\n      autocorrect=\"off\"\n      class=\"form-control\"\n      placeholder=\"{{ 'e.g.' | translate }} t12345\"\n      placeholder-no-required-hint\n      required\n    />\n  </c8y-form-group>\n\n  <button\n    title=\"{{ 'Apply' | translate }}\"\n    type=\"submit\"\n    class=\"btn btn-primary btn-lg btn-block form-group\"\n    [disabled]=\"!tenantIdSetupForm.form.valid\"\n  >\n    {{ 'Apply' | translate }}\n  </button>\n</form>\n", dependencies: [{ kind: "directive", type: i6.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i6.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: i6.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i6.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i6.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i6.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i6.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i7.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "component", type: i8.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i9.RequiredInputPlaceholderDirective, selector: "input[required], input[formControlName]" }, { kind: "pipe", type: i10.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: TenantIdSetupComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-tenant-id-setup', template: "<form #tenantIdSetupForm=\"ngForm\" class=\"loginForm\" (ngSubmit)=\"setupLoginMode()\" novalidate>\n  <div class=\"legend form-block center\" translate>Tenant setup</div>\n  <c8y-form-group class=\"tenantField\" id=\"tenantField\">\n    <label for=\"tenant\" translate>Tenant ID</label>\n    <input\n      [(ngModel)]=\"model.tenant\"\n      #tenant=\"ngModel\"\n      type=\"text\"\n      name=\"tenant\"\n      id=\"tenant\"\n      autocapitalize=\"off\"\n      autocorrect=\"off\"\n      class=\"form-control\"\n      placeholder=\"{{ 'e.g.' | translate }} t12345\"\n      placeholder-no-required-hint\n      required\n    />\n  </c8y-form-group>\n\n  <button\n    title=\"{{ 'Apply' | translate }}\"\n    type=\"submit\"\n    class=\"btn btn-primary btn-lg btn-block form-group\"\n    [disabled]=\"!tenantIdSetupForm.form.valid\"\n  >\n    {{ 'Apply' | translate }}\n  </button>\n</form>\n" }]
        }], ctorParameters: () => [{ type: i1.FetchClient }, { type: i2.AppStateService }, { type: i3.LoginService }, { type: i4.AlertService }, { type: i5.TranslateService }], propDecorators: { onChangeView: [{
                type: Output
            }] } });
//# sourceMappingURL=data:application/json;base64, 