import * as i0 from '@angular/core';
import { Injectable, EventEmitter, Component, Input, Output, ViewChild, InjectionToken, Inject, NgModule } from '@angular/core';
import * as i3$1 from '@angular/forms';
import { Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import * as i2 from '@angular/router';
import * as i3 from '@ionic/angular';
import { TapClientError } from '@iotize/tap/client/impl';
import { ConnectionState } from '@iotize/tap/protocol/api';
import * as i1 from '@iotize/ionic';
import { getFormFieldOrError, LibCommonModule, TaskManagerUiModule } from '@iotize/ionic';
import * as i6 from '@angular/common';
import { of, from } from 'rxjs';
import { map } from 'rxjs/operators';
import { createDebugger } from '@iotize/common/debug';

class TapAuthService {
    constructor() {
        try {
            this.options = JSON.parse(localStorage.getItem('TapAuthServiceStorage') || '{}');
        }
        catch (err) {
            this.options = {};
        }
        if (!this.options) {
            this.options = {};
        }
    }
    store() {
        localStorage.setItem('TapAuthServiceStorage', JSON.stringify(this.options));
    }
}
/** @nocollapse */ /** @nocollapse */ TapAuthService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: TapAuthService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
/** @nocollapse */ /** @nocollapse */ TapAuthService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: TapAuthService, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: TapAuthService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }], ctorParameters: function () { return []; } });

class DeviceLoginComponent {
    constructor(tapService, router, platform, modalController, formBuilder, tapAuth) {
        this.tapService = tapService;
        this.router = router;
        this.platform = platform;
        this.modalController = modalController;
        this.formBuilder = formBuilder;
        this.tapAuth = tapAuth;
        /**
         * Refresh session state on login
         */
        this.refreshSessionState = true;
        this.header = true;
        this.footer = true;
        this.returnUrl = undefined;
        this.closeButton = true;
        this.backButton = false;
        this.enableAutoLogin = false;
        this.enableRememberMe = true;
        this.title = 'Tap login';
        this.onError = new EventEmitter();
        this.loading = false;
        const defaultUsername = this.tapAuth.options.lastCredentials
            ? this.tapAuth.options.lastCredentials.username
            : '';
        const defaultPassword = ''; // this.tapAuth.options.lastCredentials ? this.tapAuth.options.lastCredentials.password : '';
        this.form = this.formBuilder.group({
            username: [defaultUsername, Validators.required],
            password: [
                defaultPassword,
                [
                    Validators.required,
                    Validators.minLength(1),
                    Validators.maxLength(16),
                ],
            ],
            rememberMe: [this.tapAuth.options.rememberMe],
            autoLogin: [this.tapAuth.options.autoLogin],
        });
    }
    // unregisterBackAction: any;
    get tap() {
        return this.tapService.tap;
    }
    get rememberMe() {
        return this.getField('rememberMe');
    }
    get autoLogin() {
        return this.getField('autoLogin');
    }
    get username() {
        return this.getField('username');
    }
    get password() {
        return this.getField('password');
    }
    getField(name) {
        const field = this.form.get(name);
        if (!field) {
            throw new Error(`Internal error: missing input with [formControlName]="${name}" in html template`);
        }
        return field;
    }
    ngOnInit() {
        this.sessionState$ = this.tap.auth.sessionState;
        this.connectionStateSub = this.tapService.connectionState.subscribe(async (event) => {
            if (event.newState === ConnectionState.CONNECTED) {
                if (this.pendingLoginCall) {
                    await this._execCall(this.pendingLoginCall);
                }
            }
        });
        // this.unregisterBackAction = this.platform.registerBackButtonAction(() => {
        //   this.dismiss();
        // })
    }
    // ngOnDestroy() {
    //   // if (this.unregisterBackAction) this.unregisterBackAction();
    // }
    async login() {
        this.loading = true;
        const username = this.username.value;
        const password = this.password.value;
        const rememberMe = this.rememberMe.value;
        const autoLogin = this.autoLogin.value;
        const options = { username, password, rememberMe, autoLogin };
        const loginCall = async () => {
            await this.tapService.login(username, password, this.refreshSessionState);
            return options;
        };
        await this._execCall(loginCall);
    }
    async dismiss() {
        const topOverlay = await this.modalController.getTop();
        if (topOverlay) {
            await this.modalController.dismiss(topOverlay.id);
        }
    }
    cancelAction() {
        this.pendingLoginCall = undefined;
        this.error = undefined;
        this.form.enable();
    }
    _execCall(call) {
        this.loading = true;
        return call()
            .then(async (options) => {
            this.tapAuth.options = {
                autoLogin: options.autoLogin,
                rememberMe: options.rememberMe,
            };
            if (options.rememberMe) {
                this.tapAuth.options.lastCredentials = {
                    username: options.username,
                    // password: options.password
                };
            }
            else {
                this.tapAuth.options.lastCredentials = undefined;
                this.tapAuth.options.autoLogin = false;
            }
            this.tapAuth.store();
            if (this.returnUrl) {
                await this.router.navigateByUrl(this.returnUrl);
            }
            this.pendingLoginCall = undefined;
            this.form.enable();
            await this.dismiss();
        })
            .catch((err) => {
            if (err.code === TapClientError.Code.NotConnectedError ||
                err.code === 'NfcTagLostError' ||
                err.code === 'NfcNotConnectedError') {
                this.pendingLoginCall = call;
                this.form.disable();
            }
            else {
                this._onError(err);
            }
        })
            .then(() => {
            this.loading = false;
        });
    }
    _onError(err) {
        this.error = err;
        this.onError.emit(err);
    }
}
/** @nocollapse */ /** @nocollapse */ DeviceLoginComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: DeviceLoginComponent, deps: [{ token: i1.CurrentDeviceService }, { token: i2.Router }, { token: i3.Platform }, { token: i3.ModalController }, { token: i3$1.FormBuilder }, { token: TapAuthService }], target: i0.ɵɵFactoryTarget.Component });
/** @nocollapse */ /** @nocollapse */ DeviceLoginComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.3.0", type: DeviceLoginComponent, selector: "tap-device-login", inputs: { refreshSessionState: "refreshSessionState", header: "header", footer: "footer", returnUrl: "returnUrl", closeButton: "closeButton", backButton: "backButton", enableAutoLogin: "enableAutoLogin", enableRememberMe: "enableRememberMe", title: "title" }, outputs: { onError: "onError" }, ngImport: i0, template: "<ion-header *ngIf=\"header\">\n  <ion-toolbar color=\"primary\">\n    <ion-buttons slot=\"start\">\n      <ion-back-button\n        *ngIf=\"backButton\"\n        [defaultHref]=\"'/device'\"\n      ></ion-back-button>\n      <ion-button *ngIf=\"closeButton\" (click)=\"dismiss()\">\n        <ion-icon name=\"arrow-back\"></ion-icon>\n      </ion-button>\n    </ion-buttons>\n    <ion-title class=\"text-center\">\n      {{ title }}\n    </ion-title>\n  </ion-toolbar>\n</ion-header>\n<ion-content>\n  <ion-progress-bar type=\"indeterminate\" [hidden]=\"!loading\"></ion-progress-bar>\n  <ion-grid>\n    <ion-row>\n      <ion-col class=\"ion-align-self-center\">\n        <iotize-feedback-error [error]=\"error\"></iotize-feedback-error>\n        <form (ngSubmit)=\"login()\" [formGroup]=\"form\" (keydown.enter)=\"login()\">\n          <div class=\"ion-padding\">\n            <ion-item>\n              <ion-label position=\"floating\">Username</ion-label>\n              <ion-input\n                type=\"text\"\n                [formControlName]=\"'username'\"\n                placeholder=\"Your username\"\n              ></ion-input>\n            </ion-item>\n            <ion-item>\n              <ion-label position=\"floating\">Password</ion-label>\n              <ion-input\n                type=\"password\"\n                [formControlName]=\"'password'\"\n                placeholder=\"Your password\"\n              ></ion-input>\n            </ion-item>\n            <ion-item *ngIf=\"enableRememberMe\">\n              <ion-label>Remember me</ion-label>\n              <ion-toggle [formControlName]=\"'rememberMe'\"></ion-toggle>\n            </ion-item>\n            <ion-item *ngIf=\"rememberMe.value && enableAutoLogin\">\n              <ion-label>Automatic login on connection</ion-label>\n              <ion-toggle [formControlName]=\"'autoLogin'\"></ion-toggle>\n            </ion-item>\n          </div>\n          <ion-item lines=\"none\">\n            <ion-button\n              *ngIf=\"pendingLoginCall\"\n              slot=\"end\"\n              (click)=\"cancelAction()\"\n              color=\"warning\"\n              size=\"default\"\n            >\n              <ion-icon slot=\"start\" name=\"close\"></ion-icon>\n              Cancel\n            </ion-button>\n            <ion-button\n              slot=\"end\"\n              type=\"submit\"\n              [disabled]=\"loading || pendingLoginCall\"\n              size=\"default\"\n            >\n              <ion-icon slot=\"start\" name=\"log-in\"></ion-icon>\n              Login\n            </ion-button>\n          </ion-item>\n          <ion-item lines=\"none\" *ngIf=\"pendingLoginCall\">\n            <ion-text class=\"ion-text-wrap\" slot=\"end\" color=\"warning\">\n              <ion-icon name=\"alert\"></ion-icon>\n              Please reconnect Tap to login\n            </ion-text>\n          </ion-item>\n        </form>\n      </ion-col>\n    </ion-row>\n  </ion-grid>\n</ion-content>\n<ion-footer *ngIf=\"footer\"></ion-footer>\n", styles: ["ion-grid{height:100%;justify-content:center}\n"], components: [{ type: i3.IonHeader, selector: "ion-header", inputs: ["collapse", "mode", "translucent"] }, { type: i3.IonToolbar, selector: "ion-toolbar", inputs: ["color", "mode"] }, { type: i3.IonButtons, selector: "ion-buttons", inputs: ["collapse"] }, { type: i3.IonBackButton, selector: "ion-back-button", inputs: ["color", "defaultHref", "disabled", "icon", "mode", "routerAnimation", "text", "type"] }, { type: i3.IonButton, selector: "ion-button", inputs: ["buttonType", "color", "disabled", "download", "expand", "fill", "href", "mode", "rel", "routerAnimation", "routerDirection", "shape", "size", "strong", "target", "type"] }, { type: i3.IonIcon, selector: "ion-icon", inputs: ["color", "flipRtl", "icon", "ios", "lazy", "md", "mode", "name", "sanitize", "size", "src"] }, { type: i3.IonTitle, selector: "ion-title", inputs: ["color", "size"] }, { type: i3.IonContent, selector: "ion-content", inputs: ["color", "forceOverscroll", "fullscreen", "scrollEvents", "scrollX", "scrollY"] }, { type: i3.IonProgressBar, selector: "ion-progress-bar", inputs: ["buffer", "color", "mode", "reversed", "type", "value"] }, { type: i3.IonGrid, selector: "ion-grid", inputs: ["fixed"] }, { type: i3.IonRow, selector: "ion-row" }, { type: i3.IonCol, selector: "ion-col", inputs: ["offset", "offsetLg", "offsetMd", "offsetSm", "offsetXl", "offsetXs", "pull", "pullLg", "pullMd", "pullSm", "pullXl", "pullXs", "push", "pushLg", "pushMd", "pushSm", "pushXl", "pushXs", "size", "sizeLg", "sizeMd", "sizeSm", "sizeXl", "sizeXs"] }, { type: i1.ErrorFeedbackComponent, selector: "iotize-feedback-error", inputs: ["error", "icon"] }, { type: i3.IonItem, selector: "ion-item", inputs: ["button", "color", "counter", "detail", "detailIcon", "disabled", "download", "fill", "href", "lines", "mode", "rel", "routerAnimation", "routerDirection", "shape", "target", "type"] }, { type: i3.IonLabel, selector: "ion-label", inputs: ["color", "mode", "position"] }, { type: i3.IonInput, selector: "ion-input", inputs: ["accept", "autocapitalize", "autocomplete", "autocorrect", "autofocus", "clearInput", "clearOnEdit", "color", "debounce", "disabled", "enterkeyhint", "inputmode", "max", "maxlength", "min", "minlength", "mode", "multiple", "name", "pattern", "placeholder", "readonly", "required", "size", "spellcheck", "step", "type", "value"] }, { type: i3.IonToggle, selector: "ion-toggle", inputs: ["checked", "color", "disabled", "mode", "name", "value"] }, { type: i3.IonText, selector: "ion-text", inputs: ["color", "mode"] }, { type: i3.IonFooter, selector: "ion-footer", inputs: ["collapse", "mode", "translucent"] }], directives: [{ type: i6.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i3.IonBackButtonDelegate, selector: "ion-back-button", inputs: ["defaultHref", "routerAnimation"] }, { type: i3$1.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { type: i3$1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { type: i3$1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { type: i3.TextValueAccessor, selector: "ion-input:not([type=number]),ion-textarea,ion-searchbar" }, { type: i3$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { type: i3$1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { type: i3.BooleanValueAccessor, selector: "ion-checkbox,ion-toggle" }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: DeviceLoginComponent, decorators: [{
            type: Component,
            args: [{ selector: 'tap-device-login', template: "<ion-header *ngIf=\"header\">\n  <ion-toolbar color=\"primary\">\n    <ion-buttons slot=\"start\">\n      <ion-back-button\n        *ngIf=\"backButton\"\n        [defaultHref]=\"'/device'\"\n      ></ion-back-button>\n      <ion-button *ngIf=\"closeButton\" (click)=\"dismiss()\">\n        <ion-icon name=\"arrow-back\"></ion-icon>\n      </ion-button>\n    </ion-buttons>\n    <ion-title class=\"text-center\">\n      {{ title }}\n    </ion-title>\n  </ion-toolbar>\n</ion-header>\n<ion-content>\n  <ion-progress-bar type=\"indeterminate\" [hidden]=\"!loading\"></ion-progress-bar>\n  <ion-grid>\n    <ion-row>\n      <ion-col class=\"ion-align-self-center\">\n        <iotize-feedback-error [error]=\"error\"></iotize-feedback-error>\n        <form (ngSubmit)=\"login()\" [formGroup]=\"form\" (keydown.enter)=\"login()\">\n          <div class=\"ion-padding\">\n            <ion-item>\n              <ion-label position=\"floating\">Username</ion-label>\n              <ion-input\n                type=\"text\"\n                [formControlName]=\"'username'\"\n                placeholder=\"Your username\"\n              ></ion-input>\n            </ion-item>\n            <ion-item>\n              <ion-label position=\"floating\">Password</ion-label>\n              <ion-input\n                type=\"password\"\n                [formControlName]=\"'password'\"\n                placeholder=\"Your password\"\n              ></ion-input>\n            </ion-item>\n            <ion-item *ngIf=\"enableRememberMe\">\n              <ion-label>Remember me</ion-label>\n              <ion-toggle [formControlName]=\"'rememberMe'\"></ion-toggle>\n            </ion-item>\n            <ion-item *ngIf=\"rememberMe.value && enableAutoLogin\">\n              <ion-label>Automatic login on connection</ion-label>\n              <ion-toggle [formControlName]=\"'autoLogin'\"></ion-toggle>\n            </ion-item>\n          </div>\n          <ion-item lines=\"none\">\n            <ion-button\n              *ngIf=\"pendingLoginCall\"\n              slot=\"end\"\n              (click)=\"cancelAction()\"\n              color=\"warning\"\n              size=\"default\"\n            >\n              <ion-icon slot=\"start\" name=\"close\"></ion-icon>\n              Cancel\n            </ion-button>\n            <ion-button\n              slot=\"end\"\n              type=\"submit\"\n              [disabled]=\"loading || pendingLoginCall\"\n              size=\"default\"\n            >\n              <ion-icon slot=\"start\" name=\"log-in\"></ion-icon>\n              Login\n            </ion-button>\n          </ion-item>\n          <ion-item lines=\"none\" *ngIf=\"pendingLoginCall\">\n            <ion-text class=\"ion-text-wrap\" slot=\"end\" color=\"warning\">\n              <ion-icon name=\"alert\"></ion-icon>\n              Please reconnect Tap to login\n            </ion-text>\n          </ion-item>\n        </form>\n      </ion-col>\n    </ion-row>\n  </ion-grid>\n</ion-content>\n<ion-footer *ngIf=\"footer\"></ion-footer>\n", styles: ["ion-grid{height:100%;justify-content:center}\n"] }]
        }], ctorParameters: function () { return [{ type: i1.CurrentDeviceService }, { type: i2.Router }, { type: i3.Platform }, { type: i3.ModalController }, { type: i3$1.FormBuilder }, { type: TapAuthService }]; }, propDecorators: { refreshSessionState: [{
                type: Input
            }], header: [{
                type: Input
            }], footer: [{
                type: Input
            }], returnUrl: [{
                type: Input
            }], closeButton: [{
                type: Input
            }], backButton: [{
                type: Input
            }], enableAutoLogin: [{
                type: Input
            }], enableRememberMe: [{
                type: Input
            }], title: [{
                type: Input
            }], onError: [{
                type: Output
            }] } });

const TASK_ID = 'change-user-password';
class ChangePasswordComponent {
    constructor(currentDevice, modalController, formBuilder, taskManager) {
        this.currentDevice = currentDevice;
        this.modalController = modalController;
        this.formBuilder = formBuilder;
        this.taskManager = taskManager;
        this.confirmPassword = false;
        this.askCurrentPassword = false;
        this.header = true;
        this.userId = undefined;
        this.loading = false;
        this.form = this.formBuilder.group({
            password: ['', Validators.required],
            confirmPassword: [''],
            currentPassword: [''],
        });
        this.changePasswordTask = this.taskManager.createTask({
            id: TASK_ID,
            info: {
                title: 'Change user password',
                feedback: 'User password changed!',
            },
            exec: () => {
                return this.changePassword();
            },
        });
    }
    get tap() {
        return this.currentDevice.tap;
    }
    get password() {
        return getFormFieldOrError(this.form, 'password');
    }
    get currentPassword() {
        return getFormFieldOrError(this.form, 'currentPassword');
    }
    submit() {
        this.error = undefined;
        this.changePasswordTaskComponent.execTask();
    }
    async changePassword() {
        try {
            const newPassword = this.password.value;
            if (this.askCurrentPassword) {
                await this.tap.auth.login({
                    username: this.tap.auth.sessionStateSnapshot.name,
                    password: this.currentPassword.value,
                });
            }
            this.promise$ = this.tap.auth.changePassword(newPassword, this.userId);
            await this.promise$;
            await this.modalController.dismiss();
        }
        catch (err) {
            this.showError(err);
        }
    }
    async dismiss() {
        await this.modalController.dismiss();
    }
    showError(err) {
        this.error = err;
    }
}
/** @nocollapse */ /** @nocollapse */ ChangePasswordComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: ChangePasswordComponent, deps: [{ token: i1.CurrentDeviceService }, { token: i3.ModalController }, { token: i3$1.FormBuilder }, { token: i1.TaskManagerService }], target: i0.ɵɵFactoryTarget.Component });
/** @nocollapse */ /** @nocollapse */ ChangePasswordComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "13.3.0", type: ChangePasswordComponent, selector: "tap-change-password", inputs: { confirmPassword: "confirmPassword", askCurrentPassword: "askCurrentPassword", header: "header", userId: "userId" }, viewQueries: [{ propertyName: "changePasswordTaskComponent", first: true, predicate: ["changePasswordTaskComponent"], descendants: true, static: true }], ngImport: i0, template: "<ion-header *ngIf=\"header\">\n  <ion-toolbar color=\"primary\">\n    <ion-buttons slot=\"start\">\n      <ion-button (click)=\"modalController.dismiss()\">\n        <ion-icon name=\"arrow-back\"></ion-icon>\n      </ion-button>\n    </ion-buttons>\n    <ion-title class=\"text-center\"> Change profile password </ion-title>\n  </ion-toolbar>\n</ion-header>\n<ion-content>\n  <ion-grid>\n    <ion-row>\n      <ion-col class=\"ion-align-self-center\">\n        <iotize-feedback-error [error]=\"error\"></iotize-feedback-error>\n        <form\n          (ngSubmit)=\"submit()\"\n          [formGroup]=\"form\"\n          (keydown.enter)=\"submit()\"\n        >\n          <ion-item *ngIf=\"askCurrentPassword\">\n            <ion-input\n              [formControlName]=\"'currentPassword'\"\n              placeholder=\"Current password\"\n              required\n              type=\"password\"\n            ></ion-input>\n          </ion-item>\n          <ion-item>\n            <ion-input\n              [formControlName]=\"'password'\"\n              placeholder=\"New password\"\n              required\n              type=\"password\"\n            ></ion-input>\n          </ion-item>\n          <ion-item *ngIf=\"confirmPassword\">\n            <ion-input\n              [formControlName]=\"'confirmPassword'\"\n              placeholder=\"Confirm new password\"\n              required\n              type=\"password\"\n            ></ion-input>\n          </ion-item>\n          <app-task-manager\n            #changePasswordTaskComponent\n            [task]=\"changePasswordTask\"\n          >\n            <app-task-manager-action>\n              <ion-item lines=\"none\">\n                <ion-button\n                  size=\"default\"\n                  slot=\"end\"\n                  [disabled]=\"form['invalid']\"\n                  expand=\"block\"\n                  type=\"submit\"\n                >\n                  <ion-icon name=\"create\"></ion-icon>\n                  Change password\n                </ion-button>\n              </ion-item>\n            </app-task-manager-action>\n            <app-task-manager-delayed>\n              <ion-item lines=\"none\">\n                <ion-text class=\"ion-text-wrap\" slot=\"end\" color=\"warning\">\n                  <ion-icon name=\"alert\"></ion-icon>\n                  Please reconnect Tap to change password\n                </ion-text>\n                <ion-button\n                  size=\"default\"\n                  color=\"warning\"\n                  app-task-manager-action-cancel\n                >\n                  <ion-icon name=\"close\"></ion-icon>\n                  Cancel\n                </ion-button>\n              </ion-item>\n            </app-task-manager-delayed>\n            <app-task-manager-running>\n              <ion-item lines=\"none\">\n                <ion-progress-bar type=\"indeterminate\"></ion-progress-bar>\n              </ion-item>\n            </app-task-manager-running>\n          </app-task-manager>\n        </form>\n      </ion-col>\n    </ion-row>\n  </ion-grid>\n</ion-content>\n", styles: [""], components: [{ type: i3.IonHeader, selector: "ion-header", inputs: ["collapse", "mode", "translucent"] }, { type: i3.IonToolbar, selector: "ion-toolbar", inputs: ["color", "mode"] }, { type: i3.IonButtons, selector: "ion-buttons", inputs: ["collapse"] }, { type: i3.IonButton, selector: "ion-button", inputs: ["buttonType", "color", "disabled", "download", "expand", "fill", "href", "mode", "rel", "routerAnimation", "routerDirection", "shape", "size", "strong", "target", "type"] }, { type: i3.IonIcon, selector: "ion-icon", inputs: ["color", "flipRtl", "icon", "ios", "lazy", "md", "mode", "name", "sanitize", "size", "src"] }, { type: i3.IonTitle, selector: "ion-title", inputs: ["color", "size"] }, { type: i3.IonContent, selector: "ion-content", inputs: ["color", "forceOverscroll", "fullscreen", "scrollEvents", "scrollX", "scrollY"] }, { type: i3.IonGrid, selector: "ion-grid", inputs: ["fixed"] }, { type: i3.IonRow, selector: "ion-row" }, { type: i3.IonCol, selector: "ion-col", inputs: ["offset", "offsetLg", "offsetMd", "offsetSm", "offsetXl", "offsetXs", "pull", "pullLg", "pullMd", "pullSm", "pullXl", "pullXs", "push", "pushLg", "pushMd", "pushSm", "pushXl", "pushXs", "size", "sizeLg", "sizeMd", "sizeSm", "sizeXl", "sizeXs"] }, { type: i1.ErrorFeedbackComponent, selector: "iotize-feedback-error", inputs: ["error", "icon"] }, { type: i3.IonItem, selector: "ion-item", inputs: ["button", "color", "counter", "detail", "detailIcon", "disabled", "download", "fill", "href", "lines", "mode", "rel", "routerAnimation", "routerDirection", "shape", "target", "type"] }, { type: i3.IonInput, selector: "ion-input", inputs: ["accept", "autocapitalize", "autocomplete", "autocorrect", "autofocus", "clearInput", "clearOnEdit", "color", "debounce", "disabled", "enterkeyhint", "inputmode", "max", "maxlength", "min", "minlength", "mode", "multiple", "name", "pattern", "placeholder", "readonly", "required", "size", "spellcheck", "step", "type", "value"] }, { type: i1.TaskManagerComponent, selector: "app-task-manager", inputs: ["task"] }, { type: i1.TaskManagerActionComponent, selector: "app-task-manager-action", inputs: ["context"] }, { type: i1.TaskManagerDelayedComponent, selector: "app-task-manager-delayed", inputs: ["context"] }, { type: i3.IonText, selector: "ion-text", inputs: ["color", "mode"] }, { type: i1.TaskManagerRunningComponent, selector: "app-task-manager-running", inputs: ["context"] }, { type: i3.IonProgressBar, selector: "ion-progress-bar", inputs: ["buffer", "color", "mode", "reversed", "type", "value"] }], directives: [{ type: i6.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i3$1.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { type: i3$1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { type: i3$1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { type: i3.TextValueAccessor, selector: "ion-input:not([type=number]),ion-textarea,ion-searchbar" }, { type: i3$1.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { type: i3$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { type: i3$1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { type: i1.TaskManagerActionCancelDirective, selector: "[app-task-manager-action-cancel]", outputs: ["onClick"] }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: ChangePasswordComponent, decorators: [{
            type: Component,
            args: [{ selector: 'tap-change-password', template: "<ion-header *ngIf=\"header\">\n  <ion-toolbar color=\"primary\">\n    <ion-buttons slot=\"start\">\n      <ion-button (click)=\"modalController.dismiss()\">\n        <ion-icon name=\"arrow-back\"></ion-icon>\n      </ion-button>\n    </ion-buttons>\n    <ion-title class=\"text-center\"> Change profile password </ion-title>\n  </ion-toolbar>\n</ion-header>\n<ion-content>\n  <ion-grid>\n    <ion-row>\n      <ion-col class=\"ion-align-self-center\">\n        <iotize-feedback-error [error]=\"error\"></iotize-feedback-error>\n        <form\n          (ngSubmit)=\"submit()\"\n          [formGroup]=\"form\"\n          (keydown.enter)=\"submit()\"\n        >\n          <ion-item *ngIf=\"askCurrentPassword\">\n            <ion-input\n              [formControlName]=\"'currentPassword'\"\n              placeholder=\"Current password\"\n              required\n              type=\"password\"\n            ></ion-input>\n          </ion-item>\n          <ion-item>\n            <ion-input\n              [formControlName]=\"'password'\"\n              placeholder=\"New password\"\n              required\n              type=\"password\"\n            ></ion-input>\n          </ion-item>\n          <ion-item *ngIf=\"confirmPassword\">\n            <ion-input\n              [formControlName]=\"'confirmPassword'\"\n              placeholder=\"Confirm new password\"\n              required\n              type=\"password\"\n            ></ion-input>\n          </ion-item>\n          <app-task-manager\n            #changePasswordTaskComponent\n            [task]=\"changePasswordTask\"\n          >\n            <app-task-manager-action>\n              <ion-item lines=\"none\">\n                <ion-button\n                  size=\"default\"\n                  slot=\"end\"\n                  [disabled]=\"form['invalid']\"\n                  expand=\"block\"\n                  type=\"submit\"\n                >\n                  <ion-icon name=\"create\"></ion-icon>\n                  Change password\n                </ion-button>\n              </ion-item>\n            </app-task-manager-action>\n            <app-task-manager-delayed>\n              <ion-item lines=\"none\">\n                <ion-text class=\"ion-text-wrap\" slot=\"end\" color=\"warning\">\n                  <ion-icon name=\"alert\"></ion-icon>\n                  Please reconnect Tap to change password\n                </ion-text>\n                <ion-button\n                  size=\"default\"\n                  color=\"warning\"\n                  app-task-manager-action-cancel\n                >\n                  <ion-icon name=\"close\"></ion-icon>\n                  Cancel\n                </ion-button>\n              </ion-item>\n            </app-task-manager-delayed>\n            <app-task-manager-running>\n              <ion-item lines=\"none\">\n                <ion-progress-bar type=\"indeterminate\"></ion-progress-bar>\n              </ion-item>\n            </app-task-manager-running>\n          </app-task-manager>\n        </form>\n      </ion-col>\n    </ion-row>\n  </ion-grid>\n</ion-content>\n", styles: [""] }]
        }], ctorParameters: function () { return [{ type: i1.CurrentDeviceService }, { type: i3.ModalController }, { type: i3$1.FormBuilder }, { type: i1.TaskManagerService }]; }, propDecorators: { changePasswordTaskComponent: [{
                type: ViewChild,
                args: ['changePasswordTaskComponent', { static: true }]
            }], confirmPassword: [{
                type: Input
            }], askCurrentPassword: [{
                type: Input
            }], header: [{
                type: Input
            }], userId: [{
                type: Input
            }] } });

const debug = createDebugger('@iotize/ionic:auth');

const DEVICE_AUTH_GUARD_CONFIG = new InjectionToken('DEVICE_AUTH_GUARD_CONFIG');
class DeviceAuthGuard {
    // private routerData?: DeviceAuthGuardRouteData;
    constructor(tapService, router, config) {
        this.tapService = tapService;
        this.router = router;
        this.config = config;
        this.subscriptions = {};
        // this.setupSessionStateListener();
    }
    canDeactivate(component, currentRoute, currentState, nextState) {
        // if (this.sessionStateSub) {
        //   this.sessionStateSub.unsubscribe();
        // }
        return true;
    }
    canActivate(route, state) {
        this.setupSessionStateListener(route, state);
        if (!route.data.username) {
            return of(true);
        }
        debug(`Check is login as "${route.data.username}" to access "${route.url}"`);
        return from(this.tapService.isLoggedInAs(route.data.username)).pipe(map((isLoggedAs) => {
            if (!isLoggedAs) {
                this.onUnauthorized(state.url, route).catch((err) => {
                    console.warn(err);
                });
            }
            return isLoggedAs;
        }));
    }
    async onUnauthorized(returnUrl, activatedRoute) {
        debug(`Not authorized to access this route "${activatedRoute.url}" -> redirect to "${this.config.loginUrl}"`);
        await this.router.navigate([this.config.loginUrl], {
            queryParams: { returnUrl: returnUrl },
        });
    }
    /**
     * Listen to session state changes for the given route. It it's the active route, we redirect to login
     * @param activatedRoute  ActivatedRouteSnapshot
     * @param state RouterStateSnapshot
     */
    setupSessionStateListener(activatedRoute, state) {
        if (state.url in this.subscriptions) {
            return this.subscriptions[state.url];
        }
        const subscription = this.tapService.sessionState.subscribe(async (event) => {
            if (this.router.isActive(state.url, true)) {
                const routeData = activatedRoute.data;
                if (routeData &&
                    routeData.username &&
                    !routeData.disableAuthGuardOnPage) {
                    const usernames = Array.isArray(routeData.username)
                        ? routeData.username
                        : [routeData.username];
                    debug('DeviceAuthGuard', 'Active route: ', state.url, 'requires username(s)', usernames, `Current username: ${event.name}`);
                    if (usernames.indexOf(event.name) === -1) {
                        await this.onUnauthorized(state.url, activatedRoute);
                    }
                }
            }
        });
        this.subscriptions[state.url] = subscription;
        return subscription;
    }
}
/** @nocollapse */ /** @nocollapse */ DeviceAuthGuard.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: DeviceAuthGuard, deps: [{ token: i1.CurrentDeviceService }, { token: i2.Router }, { token: DEVICE_AUTH_GUARD_CONFIG }], target: i0.ɵɵFactoryTarget.Injectable });
/** @nocollapse */ /** @nocollapse */ DeviceAuthGuard.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: DeviceAuthGuard, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: DeviceAuthGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }], ctorParameters: function () { return [{ type: i1.CurrentDeviceService }, { type: i2.Router }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [DEVICE_AUTH_GUARD_CONFIG]
                }] }]; } });

class TapAuthModule {
}
/** @nocollapse */ /** @nocollapse */ TapAuthModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: TapAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
/** @nocollapse */ /** @nocollapse */ TapAuthModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: TapAuthModule, declarations: [DeviceLoginComponent, ChangePasswordComponent], imports: [LibCommonModule,
        FormsModule,
        ReactiveFormsModule,
        TaskManagerUiModule], exports: [DeviceLoginComponent, ChangePasswordComponent] });
/** @nocollapse */ /** @nocollapse */ TapAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: TapAuthModule, providers: [DeviceAuthGuard], imports: [[
            LibCommonModule,
            FormsModule,
            ReactiveFormsModule,
            TaskManagerUiModule,
        ]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.0", ngImport: i0, type: TapAuthModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [DeviceLoginComponent, ChangePasswordComponent],
                    exports: [DeviceLoginComponent, ChangePasswordComponent],
                    providers: [DeviceAuthGuard],
                    entryComponents: [DeviceLoginComponent, ChangePasswordComponent],
                    imports: [
                        LibCommonModule,
                        FormsModule,
                        ReactiveFormsModule,
                        TaskManagerUiModule,
                    ],
                }]
        }] });

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

export { ChangePasswordComponent, DEVICE_AUTH_GUARD_CONFIG, DeviceAuthGuard, DeviceLoginComponent, TapAuthModule, TapAuthService };
//# sourceMappingURL=iotize-ionic-auth.mjs.map
