import { __awaiter } from 'tslib';
import { ɵɵdefineInjectable, ɵsetClassMetadata, Injectable, ɵɵelement, ɵɵproperty, ɵɵgetCurrentView, ɵɵelementStart, ɵɵlistener, ɵɵrestoreView, ɵɵnextContext, ɵɵelementEnd, ɵɵtemplate, ɵɵtext, ɵɵadvance, ɵɵtextInterpolate1, EventEmitter, ɵɵdirectiveInject, ɵɵdefineComponent, Component, Input, Output, ɵɵviewQuery, ɵɵqueryRefresh, ɵɵloadQuery, ViewChild, InjectionToken, ɵɵinject, Inject, ɵɵdefineNgModule, ɵɵdefineInjector, ɵɵsetNgModuleScope, NgModule } from '@angular/core';
import { Validators, FormBuilder, ɵangular_packages_forms_forms_ba, NgControlStatusGroup, FormGroupDirective, NgControlStatus, FormControlName, RequiredValidator, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { Platform, ModalController, IonContent, IonProgressBar, IonGrid, IonRow, IonCol, IonItem, IonLabel, IonInput, TextValueAccessor, IonButton, IonIcon, IonHeader, IonToolbar, IonButtons, IonTitle, IonBackButton, IonBackButtonDelegate, IonToggle, BooleanValueAccessor, IonText, IonFooter } from '@ionic/angular';
import { TapClientError } from '@iotize/tap/client/impl';
import { ConnectionState } from '@iotize/tap/protocol/api';
import { CurrentDeviceService, ErrorFeedbackComponent, getFormFieldOrError, TaskManagerService, TaskManagerComponent, TaskManagerActionComponent, TaskManagerDelayedComponent, TaskManagerActionCancelDirective, TaskManagerRunningComponent, LibCommonModule, TaskManagerUiModule } from '@iotize/ionic';
import { NgIf } 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 */ TapAuthService.ɵfac = function TapAuthService_Factory(t) { return new (t || TapAuthService)(); };
/** @nocollapse */ TapAuthService.ɵprov = ɵɵdefineInjectable({ token: TapAuthService, factory: TapAuthService.ɵfac, providedIn: 'root' });
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵsetClassMetadata(TapAuthService, [{
        type: Injectable,
        args: [{
                providedIn: 'root',
            }]
    }], function () { return []; }, null); })();

function DeviceLoginComponent_ion_header_0_ion_back_button_3_Template(rf, ctx) { if (rf & 1) {
    ɵɵelement(0, "ion-back-button", 19);
} if (rf & 2) {
    ɵɵproperty("defaultHref", "/device");
} }
function DeviceLoginComponent_ion_header_0_ion_button_4_Template(rf, ctx) { if (rf & 1) {
    const _r9 = ɵɵgetCurrentView();
    ɵɵelementStart(0, "ion-button", 20);
    ɵɵlistener("click", function DeviceLoginComponent_ion_header_0_ion_button_4_Template_ion_button_click_0_listener() { ɵɵrestoreView(_r9); const ctx_r8 = ɵɵnextContext(2); return ctx_r8.dismiss(); });
    ɵɵelement(1, "ion-icon", 21);
    ɵɵelementEnd();
} }
function DeviceLoginComponent_ion_header_0_Template(rf, ctx) { if (rf & 1) {
    ɵɵelementStart(0, "ion-header");
    ɵɵelementStart(1, "ion-toolbar", 14);
    ɵɵelementStart(2, "ion-buttons", 15);
    ɵɵtemplate(3, DeviceLoginComponent_ion_header_0_ion_back_button_3_Template, 1, 1, "ion-back-button", 16);
    ɵɵtemplate(4, DeviceLoginComponent_ion_header_0_ion_button_4_Template, 2, 0, "ion-button", 17);
    ɵɵelementEnd();
    ɵɵelementStart(5, "ion-title", 18);
    ɵɵtext(6);
    ɵɵelementEnd();
    ɵɵelementEnd();
    ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r0 = ɵɵnextContext();
    ɵɵadvance(3);
    ɵɵproperty("ngIf", ctx_r0.backButton);
    ɵɵadvance(1);
    ɵɵproperty("ngIf", ctx_r0.closeButton);
    ɵɵadvance(2);
    ɵɵtextInterpolate1(" ", ctx_r0.title, " ");
} }
function DeviceLoginComponent_ion_item_17_Template(rf, ctx) { if (rf & 1) {
    ɵɵelementStart(0, "ion-item");
    ɵɵelementStart(1, "ion-label");
    ɵɵtext(2, "Remember me");
    ɵɵelementEnd();
    ɵɵelement(3, "ion-toggle", 22);
    ɵɵelementEnd();
} if (rf & 2) {
    ɵɵadvance(3);
    ɵɵproperty("formControlName", "rememberMe");
} }
function DeviceLoginComponent_ion_item_18_Template(rf, ctx) { if (rf & 1) {
    ɵɵelementStart(0, "ion-item");
    ɵɵelementStart(1, "ion-label");
    ɵɵtext(2, "Automatic login on connection");
    ɵɵelementEnd();
    ɵɵelement(3, "ion-toggle", 22);
    ɵɵelementEnd();
} if (rf & 2) {
    ɵɵadvance(3);
    ɵɵproperty("formControlName", "autoLogin");
} }
function DeviceLoginComponent_ion_button_20_Template(rf, ctx) { if (rf & 1) {
    const _r11 = ɵɵgetCurrentView();
    ɵɵelementStart(0, "ion-button", 23);
    ɵɵlistener("click", function DeviceLoginComponent_ion_button_20_Template_ion_button_click_0_listener() { ɵɵrestoreView(_r11); const ctx_r10 = ɵɵnextContext(); return ctx_r10.cancelAction(); });
    ɵɵelement(1, "ion-icon", 24);
    ɵɵtext(2, " Cancel ");
    ɵɵelementEnd();
} }
function DeviceLoginComponent_ion_item_24_Template(rf, ctx) { if (rf & 1) {
    ɵɵelementStart(0, "ion-item", 9);
    ɵɵelementStart(1, "ion-text", 25);
    ɵɵelement(2, "ion-icon", 26);
    ɵɵtext(3, " Please reconnect Tap to login ");
    ɵɵelementEnd();
    ɵɵelementEnd();
} }
function DeviceLoginComponent_ion_footer_25_Template(rf, ctx) { if (rf & 1) {
    ɵɵelement(0, "ion-footer");
} }
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],
            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((event) => __awaiter(this, void 0, void 0, function* () {
            if (event.newState === ConnectionState.CONNECTED) {
                if (this.pendingLoginCall) {
                    yield this._execCall(this.pendingLoginCall);
                }
            }
        }));
        // this.unregisterBackAction = this.platform.registerBackButtonAction(() => {
        //   this.dismiss();
        // })
    }
    // ngOnDestroy() {
    //   // if (this.unregisterBackAction) this.unregisterBackAction();
    // }
    login() {
        return __awaiter(this, void 0, void 0, function* () {
            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 = () => __awaiter(this, void 0, void 0, function* () {
                yield this.tapService.login(username, password, this.refreshSessionState);
                return options;
            });
            yield this._execCall(loginCall);
        });
    }
    dismiss() {
        return __awaiter(this, void 0, void 0, function* () {
            const topOverlay = yield this.modalController.getTop();
            if (topOverlay) {
                yield this.modalController.dismiss(topOverlay.id);
            }
        });
    }
    cancelAction() {
        this.pendingLoginCall = undefined;
        this.error = undefined;
        this.form.enable();
    }
    _execCall(call) {
        this.loading = true;
        return call()
            .then((options) => __awaiter(this, void 0, void 0, function* () {
            this.tapAuth.options = {
                autoLogin: options.autoLogin,
                rememberMe: options.rememberMe,
            };
            if (options.rememberMe) {
                this.tapAuth.options.lastCredentials = {
                    username: options.username,
                };
            }
            else {
                this.tapAuth.options.lastCredentials = undefined;
                this.tapAuth.options.autoLogin = false;
            }
            this.tapAuth.store();
            if (this.returnUrl) {
                yield this.router.navigateByUrl(this.returnUrl);
            }
            this.pendingLoginCall = undefined;
            this.form.enable();
            yield 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 */ DeviceLoginComponent.ɵfac = function DeviceLoginComponent_Factory(t) { return new (t || DeviceLoginComponent)(ɵɵdirectiveInject(CurrentDeviceService), ɵɵdirectiveInject(Router), ɵɵdirectiveInject(Platform), ɵɵdirectiveInject(ModalController), ɵɵdirectiveInject(FormBuilder), ɵɵdirectiveInject(TapAuthService)); };
/** @nocollapse */ DeviceLoginComponent.ɵcmp = ɵɵdefineComponent({ type: DeviceLoginComponent, selectors: [["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" }, decls: 26, vars: 12, consts: [[4, "ngIf"], ["type", "indeterminate", 3, "hidden"], [1, "ion-align-self-center"], [3, "error"], [3, "formGroup", "ngSubmit", "keydown.enter"], [1, "ion-padding"], ["position", "floating"], ["type", "text", "placeholder", "Your username", 3, "formControlName"], ["type", "password", "placeholder", "Your password", 3, "formControlName"], ["lines", "none"], ["slot", "end", "color", "warning", "size", "default", 3, "click", 4, "ngIf"], ["slot", "end", "type", "submit", "size", "default", 3, "disabled"], ["slot", "start", "name", "log-in"], ["lines", "none", 4, "ngIf"], ["color", "primary"], ["slot", "start"], [3, "defaultHref", 4, "ngIf"], [3, "click", 4, "ngIf"], [1, "text-center"], [3, "defaultHref"], [3, "click"], ["name", "arrow-back"], [3, "formControlName"], ["slot", "end", "color", "warning", "size", "default", 3, "click"], ["slot", "start", "name", "close"], ["slot", "end", "color", "warning", 1, "ion-text-wrap"], ["name", "alert"]], template: function DeviceLoginComponent_Template(rf, ctx) { if (rf & 1) {
        ɵɵtemplate(0, DeviceLoginComponent_ion_header_0_Template, 7, 3, "ion-header", 0);
        ɵɵelementStart(1, "ion-content");
        ɵɵelement(2, "ion-progress-bar", 1);
        ɵɵelementStart(3, "ion-grid");
        ɵɵelementStart(4, "ion-row");
        ɵɵelementStart(5, "ion-col", 2);
        ɵɵelement(6, "iotize-feedback-error", 3);
        ɵɵelementStart(7, "form", 4);
        ɵɵlistener("ngSubmit", function DeviceLoginComponent_Template_form_ngSubmit_7_listener() { return ctx.login(); })("keydown.enter", function DeviceLoginComponent_Template_form_keydown_enter_7_listener() { return ctx.login(); });
        ɵɵelementStart(8, "div", 5);
        ɵɵelementStart(9, "ion-item");
        ɵɵelementStart(10, "ion-label", 6);
        ɵɵtext(11, "Username");
        ɵɵelementEnd();
        ɵɵelement(12, "ion-input", 7);
        ɵɵelementEnd();
        ɵɵelementStart(13, "ion-item");
        ɵɵelementStart(14, "ion-label", 6);
        ɵɵtext(15, "Password");
        ɵɵelementEnd();
        ɵɵelement(16, "ion-input", 8);
        ɵɵelementEnd();
        ɵɵtemplate(17, DeviceLoginComponent_ion_item_17_Template, 4, 1, "ion-item", 0);
        ɵɵtemplate(18, DeviceLoginComponent_ion_item_18_Template, 4, 1, "ion-item", 0);
        ɵɵelementEnd();
        ɵɵelementStart(19, "ion-item", 9);
        ɵɵtemplate(20, DeviceLoginComponent_ion_button_20_Template, 3, 0, "ion-button", 10);
        ɵɵelementStart(21, "ion-button", 11);
        ɵɵelement(22, "ion-icon", 12);
        ɵɵtext(23, " Login ");
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵtemplate(24, DeviceLoginComponent_ion_item_24_Template, 4, 0, "ion-item", 13);
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵtemplate(25, DeviceLoginComponent_ion_footer_25_Template, 1, 0, "ion-footer", 0);
    } if (rf & 2) {
        ɵɵproperty("ngIf", ctx.header);
        ɵɵadvance(2);
        ɵɵproperty("hidden", !ctx.loading);
        ɵɵadvance(4);
        ɵɵproperty("error", ctx.error);
        ɵɵadvance(1);
        ɵɵproperty("formGroup", ctx.form);
        ɵɵadvance(5);
        ɵɵproperty("formControlName", "username");
        ɵɵadvance(4);
        ɵɵproperty("formControlName", "password");
        ɵɵadvance(1);
        ɵɵproperty("ngIf", ctx.enableRememberMe);
        ɵɵadvance(1);
        ɵɵproperty("ngIf", ctx.rememberMe.value && ctx.enableAutoLogin);
        ɵɵadvance(2);
        ɵɵproperty("ngIf", ctx.pendingLoginCall);
        ɵɵadvance(1);
        ɵɵproperty("disabled", ctx.loading || ctx.pendingLoginCall);
        ɵɵadvance(3);
        ɵɵproperty("ngIf", ctx.pendingLoginCall);
        ɵɵadvance(1);
        ɵɵproperty("ngIf", ctx.footer);
    } }, directives: [NgIf, IonContent, IonProgressBar, IonGrid, IonRow, IonCol, ErrorFeedbackComponent, ɵangular_packages_forms_forms_ba, NgControlStatusGroup, FormGroupDirective, IonItem, IonLabel, IonInput, TextValueAccessor, NgControlStatus, FormControlName, IonButton, IonIcon, IonHeader, IonToolbar, IonButtons, IonTitle, IonBackButton, IonBackButtonDelegate, IonToggle, BooleanValueAccessor, IonText, IonFooter], styles: ["ion-grid[_ngcontent-%COMP%]{height:100%;justify-content:center}"] });
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵsetClassMetadata(DeviceLoginComponent, [{
        type: Component,
        args: [{
                selector: 'tap-device-login',
                templateUrl: './device-login.component.html',
                styleUrls: ['./device-login.component.scss'],
            }]
    }], function () { return [{ type: CurrentDeviceService }, { type: Router }, { type: Platform }, { type: ModalController }, { type: FormBuilder }, { type: TapAuthService }]; }, { 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 _c0 = ["changePasswordTaskComponent"];
function ChangePasswordComponent_ion_header_0_Template(rf, ctx) { if (rf & 1) {
    const _r5 = ɵɵgetCurrentView();
    ɵɵelementStart(0, "ion-header");
    ɵɵelementStart(1, "ion-toolbar", 15);
    ɵɵelementStart(2, "ion-buttons", 16);
    ɵɵelementStart(3, "ion-button", 17);
    ɵɵlistener("click", function ChangePasswordComponent_ion_header_0_Template_ion_button_click_3_listener() { ɵɵrestoreView(_r5); const ctx_r4 = ɵɵnextContext(); return ctx_r4.modalController.dismiss(); });
    ɵɵelement(4, "ion-icon", 18);
    ɵɵelementEnd();
    ɵɵelementEnd();
    ɵɵelementStart(5, "ion-title", 19);
    ɵɵtext(6, " Change profile password ");
    ɵɵelementEnd();
    ɵɵelementEnd();
    ɵɵelementEnd();
} }
function ChangePasswordComponent_ion_item_7_Template(rf, ctx) { if (rf & 1) {
    ɵɵelementStart(0, "ion-item");
    ɵɵelement(1, "ion-input", 20);
    ɵɵelementEnd();
} if (rf & 2) {
    ɵɵadvance(1);
    ɵɵproperty("formControlName", "currentPassword");
} }
function ChangePasswordComponent_ion_item_10_Template(rf, ctx) { if (rf & 1) {
    ɵɵelementStart(0, "ion-item");
    ɵɵelement(1, "ion-input", 21);
    ɵɵelementEnd();
} if (rf & 2) {
    ɵɵadvance(1);
    ɵɵproperty("formControlName", "confirmPassword");
} }
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();
    }
    changePassword() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const newPassword = this.password.value;
                if (this.askCurrentPassword) {
                    yield this.tap.auth.login({
                        username: this.tap.auth.sessionStateSnapshot.name,
                        password: this.currentPassword.value,
                    });
                }
                this.promise$ = this.tap.auth.changePassword(newPassword, this.userId);
                yield this.promise$;
                yield this.modalController.dismiss();
            }
            catch (err) {
                this.showError(err);
            }
        });
    }
    dismiss() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.modalController.dismiss();
        });
    }
    showError(err) {
        this.error = err;
    }
}
/** @nocollapse */ ChangePasswordComponent.ɵfac = function ChangePasswordComponent_Factory(t) { return new (t || ChangePasswordComponent)(ɵɵdirectiveInject(CurrentDeviceService), ɵɵdirectiveInject(ModalController), ɵɵdirectiveInject(FormBuilder), ɵɵdirectiveInject(TaskManagerService)); };
/** @nocollapse */ ChangePasswordComponent.ɵcmp = ɵɵdefineComponent({ type: ChangePasswordComponent, selectors: [["tap-change-password"]], viewQuery: function ChangePasswordComponent_Query(rf, ctx) { if (rf & 1) {
        ɵɵviewQuery(_c0, 3);
    } if (rf & 2) {
        let _t;
        ɵɵqueryRefresh(_t = ɵɵloadQuery()) && (ctx.changePasswordTaskComponent = _t.first);
    } }, inputs: { confirmPassword: "confirmPassword", askCurrentPassword: "askCurrentPassword", header: "header", userId: "userId" }, decls: 29, vars: 8, consts: [[4, "ngIf"], [1, "ion-align-self-center"], [3, "error"], [3, "formGroup", "ngSubmit", "keydown.enter"], ["placeholder", "New password", "required", "", "type", "password", 3, "formControlName"], [3, "task"], ["changePasswordTaskComponent", ""], ["lines", "none"], ["size", "default", "slot", "end", "expand", "block", "type", "submit", 3, "disabled"], ["name", "create"], ["slot", "end", "color", "warning", 1, "ion-text-wrap"], ["name", "alert"], ["size", "default", "color", "warning", "app-task-manager-action-cancel", ""], ["name", "close"], ["type", "indeterminate"], ["color", "primary"], ["slot", "start"], [3, "click"], ["name", "arrow-back"], [1, "text-center"], ["placeholder", "Current password", "required", "", "type", "password", 3, "formControlName"], ["placeholder", "Confirm new password", "required", "", "type", "password", 3, "formControlName"]], template: function ChangePasswordComponent_Template(rf, ctx) { if (rf & 1) {
        ɵɵtemplate(0, ChangePasswordComponent_ion_header_0_Template, 7, 0, "ion-header", 0);
        ɵɵelementStart(1, "ion-content");
        ɵɵelementStart(2, "ion-grid");
        ɵɵelementStart(3, "ion-row");
        ɵɵelementStart(4, "ion-col", 1);
        ɵɵelement(5, "iotize-feedback-error", 2);
        ɵɵelementStart(6, "form", 3);
        ɵɵlistener("ngSubmit", function ChangePasswordComponent_Template_form_ngSubmit_6_listener() { return ctx.submit(); })("keydown.enter", function ChangePasswordComponent_Template_form_keydown_enter_6_listener() { return ctx.submit(); });
        ɵɵtemplate(7, ChangePasswordComponent_ion_item_7_Template, 2, 1, "ion-item", 0);
        ɵɵelementStart(8, "ion-item");
        ɵɵelement(9, "ion-input", 4);
        ɵɵelementEnd();
        ɵɵtemplate(10, ChangePasswordComponent_ion_item_10_Template, 2, 1, "ion-item", 0);
        ɵɵelementStart(11, "app-task-manager", 5, 6);
        ɵɵelementStart(13, "app-task-manager-action");
        ɵɵelementStart(14, "ion-item", 7);
        ɵɵelementStart(15, "ion-button", 8);
        ɵɵelement(16, "ion-icon", 9);
        ɵɵtext(17, " Change password ");
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementStart(18, "app-task-manager-delayed");
        ɵɵelementStart(19, "ion-item", 7);
        ɵɵelementStart(20, "ion-text", 10);
        ɵɵelement(21, "ion-icon", 11);
        ɵɵtext(22, " Please reconnect Tap to change password ");
        ɵɵelementEnd();
        ɵɵelementStart(23, "ion-button", 12);
        ɵɵelement(24, "ion-icon", 13);
        ɵɵtext(25, " Cancel ");
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementStart(26, "app-task-manager-running");
        ɵɵelementStart(27, "ion-item", 7);
        ɵɵelement(28, "ion-progress-bar", 14);
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
        ɵɵelementEnd();
    } if (rf & 2) {
        ɵɵproperty("ngIf", ctx.header);
        ɵɵadvance(5);
        ɵɵproperty("error", ctx.error);
        ɵɵadvance(1);
        ɵɵproperty("formGroup", ctx.form);
        ɵɵadvance(1);
        ɵɵproperty("ngIf", ctx.askCurrentPassword);
        ɵɵadvance(2);
        ɵɵproperty("formControlName", "password");
        ɵɵadvance(1);
        ɵɵproperty("ngIf", ctx.confirmPassword);
        ɵɵadvance(1);
        ɵɵproperty("task", ctx.changePasswordTask);
        ɵɵadvance(4);
        ɵɵproperty("disabled", ctx.form["invalid"]);
    } }, directives: [NgIf, IonContent, IonGrid, IonRow, IonCol, ErrorFeedbackComponent, ɵangular_packages_forms_forms_ba, NgControlStatusGroup, FormGroupDirective, IonItem, IonInput, TextValueAccessor, RequiredValidator, NgControlStatus, FormControlName, TaskManagerComponent, TaskManagerActionComponent, IonButton, IonIcon, TaskManagerDelayedComponent, IonText, TaskManagerActionCancelDirective, TaskManagerRunningComponent, IonProgressBar, IonHeader, IonToolbar, IonButtons, IonTitle], styles: [""] });
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵsetClassMetadata(ChangePasswordComponent, [{
        type: Component,
        args: [{
                selector: 'tap-change-password',
                templateUrl: './change-password.component.html',
                styleUrls: ['./change-password.component.scss'],
            }]
    }], function () { return [{ type: CurrentDeviceService }, { type: ModalController }, { type: FormBuilder }, { type: TaskManagerService }]; }, { 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;
        }));
    }
    onUnauthorized(returnUrl, activatedRoute) {
        return __awaiter(this, void 0, void 0, function* () {
            debug(`Not authorized to access this route "${activatedRoute.url}" -> redirect to "${this.config.loginUrl}"`);
            yield 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((event) => __awaiter(this, void 0, void 0, function* () {
            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) {
                        yield this.onUnauthorized(state.url, activatedRoute);
                    }
                }
            }
        }));
        this.subscriptions[state.url] = subscription;
        return subscription;
    }
}
/** @nocollapse */ DeviceAuthGuard.ɵfac = function DeviceAuthGuard_Factory(t) { return new (t || DeviceAuthGuard)(ɵɵinject(CurrentDeviceService), ɵɵinject(Router), ɵɵinject(DEVICE_AUTH_GUARD_CONFIG)); };
/** @nocollapse */ DeviceAuthGuard.ɵprov = ɵɵdefineInjectable({ token: DeviceAuthGuard, factory: DeviceAuthGuard.ɵfac, providedIn: 'root' });
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵsetClassMetadata(DeviceAuthGuard, [{
        type: Injectable,
        args: [{
                providedIn: 'root',
            }]
    }], function () { return [{ type: CurrentDeviceService }, { type: Router }, { type: undefined, decorators: [{
                type: Inject,
                args: [DEVICE_AUTH_GUARD_CONFIG]
            }] }]; }, null); })();

class TapAuthModule {
}
/** @nocollapse */ TapAuthModule.ɵfac = function TapAuthModule_Factory(t) { return new (t || TapAuthModule)(); };
/** @nocollapse */ TapAuthModule.ɵmod = ɵɵdefineNgModule({ type: TapAuthModule });
/** @nocollapse */ TapAuthModule.ɵinj = ɵɵdefineInjector({ providers: [DeviceAuthGuard], imports: [[
            LibCommonModule,
            FormsModule,
            ReactiveFormsModule,
            TaskManagerUiModule,
        ]] });
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && ɵɵsetNgModuleScope(TapAuthModule, { declarations: [DeviceLoginComponent, ChangePasswordComponent], imports: [LibCommonModule,
        FormsModule,
        ReactiveFormsModule,
        TaskManagerUiModule], exports: [DeviceLoginComponent, ChangePasswordComponent] }); })();
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵsetClassMetadata(TapAuthModule, [{
        type: NgModule,
        args: [{
                declarations: [DeviceLoginComponent, ChangePasswordComponent],
                exports: [DeviceLoginComponent, ChangePasswordComponent],
                providers: [DeviceAuthGuard],
                entryComponents: [DeviceLoginComponent, ChangePasswordComponent],
                imports: [
                    LibCommonModule,
                    FormsModule,
                    ReactiveFormsModule,
                    TaskManagerUiModule,
                ],
            }]
    }], null, null); })();

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

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