(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/forms'), require('@angular/router'), require('@ionic/angular'), require('@iotize/tap/client/impl'), require('@iotize/tap/protocol/api'), require('@iotize/ionic'), require('rxjs'), require('rxjs/operators'), require('@iotize/common/debug')) :
    typeof define === 'function' && define.amd ? define('@iotize/ionic/auth', ['exports', '@angular/core', '@angular/forms', '@angular/router', '@ionic/angular', '@iotize/tap/client/impl', '@iotize/tap/protocol/api', '@iotize/ionic', 'rxjs', 'rxjs/operators', '@iotize/common/debug'], factory) :
    (global = global || self, factory((global.iotize = global.iotize || {}, global.iotize.ionic = global.iotize.ionic || {}, global.iotize.ionic.auth = {}), global.ng.core, global.ng.forms, global.ng.router, global.angular, global.impl, global.api, global.iotize.ionic, global.rxjs, global.rxjs.operators, global.debug$1));
}(this, (function (exports, core, forms, router, angular, impl, api, ionic, rxjs, operators, debug$1) { 'use strict';

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise */

    var extendStatics = function(d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };

    function __extends(d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }

    var __assign = function() {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };

    function __rest(s, e) {
        var t = {};
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
            t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }

    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }

    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); }
    }

    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
    }

    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    function __createBinding(o, m, k, k2) {
        if (k2 === undefined) k2 = k;
        o[k2] = m[k];
    }

    function __exportStar(m, exports) {
        for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
    }

    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m) return m.call(o);
        if (o && typeof o.length === "number") return {
            next: function () {
                if (o && i >= o.length) o = void 0;
                return { value: o && o[i++], done: !o };
            }
        };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }

    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m) return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
        }
        catch (error) { e = { error: error }; }
        finally {
            try {
                if (r && !r.done && (m = i["return"])) m.call(i);
            }
            finally { if (e) throw e.error; }
        }
        return ar;
    }

    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }

    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    };

    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }

    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
        function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
    }

    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }

    function __asyncValues(o) {
        if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
    }

    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
        return cooked;
    };

    function __importStar(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
        result.default = mod;
        return result;
    }

    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }

    function __classPrivateFieldGet(receiver, privateMap) {
        if (!privateMap.has(receiver)) {
            throw new TypeError("attempted to get private field on non-instance");
        }
        return privateMap.get(receiver);
    }

    function __classPrivateFieldSet(receiver, privateMap, value) {
        if (!privateMap.has(receiver)) {
            throw new TypeError("attempted to set private field on non-instance");
        }
        privateMap.set(receiver, value);
        return value;
    }

    /**
     * @fileoverview added by tsickle
     * Generated from: lib/tap-auth.service.ts
     * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
     */
    var TapAuthService = /** @class */ (function () {
        function TapAuthService() {
            try {
                this.options = JSON.parse(localStorage.getItem('TapAuthServiceStorage') || '{}');
            }
            catch (err) {
                this.options = {};
            }
            if (!this.options) {
                this.options = {};
            }
        }
        /**
         * @return {?}
         */
        TapAuthService.prototype.store = /**
         * @return {?}
         */
        function () {
            localStorage.setItem('TapAuthServiceStorage', JSON.stringify(this.options));
        };
        TapAuthService.decorators = [
            { type: core.Injectable, args: [{
                        providedIn: 'root'
                    },] }
        ];
        /** @nocollapse */
        TapAuthService.ctorParameters = function () { return []; };
        /** @nocollapse */ TapAuthService.ɵprov = core.ɵɵdefineInjectable({ factory: function TapAuthService_Factory() { return new TapAuthService(); }, token: TapAuthService, providedIn: "root" });
        return TapAuthService;
    }());
    if (false) {
        /** @type {?} */
        TapAuthService.prototype.options;
    }

    /**
     * @fileoverview added by tsickle
     * Generated from: lib/device-login/device-login.component.ts
     * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
     */
    /**
     * @record
     */
    function LoginOption() { }
    if (false) {
        /** @type {?} */
        LoginOption.prototype.username;
        /** @type {?} */
        LoginOption.prototype.password;
        /** @type {?} */
        LoginOption.prototype.rememberMe;
        /** @type {?} */
        LoginOption.prototype.autoLogin;
    }
    var DeviceLoginComponent = /** @class */ (function () {
        function DeviceLoginComponent(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 core.EventEmitter();
            this.promise$ = undefined;
            this.loading = false;
            /** @type {?} */
            var defaultUsername = this.tapAuth.options.lastCredentials ? this.tapAuth.options.lastCredentials.username : '';
            /** @type {?} */
            var defaultPassword = '';
            this.form = this.formBuilder.group({
                username: [defaultUsername, forms.Validators.required],
                password: [defaultPassword],
                rememberMe: [this.tapAuth.options.rememberMe],
                autoLogin: [this.tapAuth.options.autoLogin]
            });
        }
        Object.defineProperty(DeviceLoginComponent.prototype, "tap", {
            // unregisterBackAction: any;
            get: 
            // unregisterBackAction: any;
            /**
             * @return {?}
             */
            function () {
                return this.tapService.tap;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DeviceLoginComponent.prototype, "rememberMe", {
            get: /**
             * @return {?}
             */
            function () {
                return this.getField('rememberMe');
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DeviceLoginComponent.prototype, "autoLogin", {
            get: /**
             * @return {?}
             */
            function () {
                return this.getField('autoLogin');
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DeviceLoginComponent.prototype, "username", {
            get: /**
             * @return {?}
             */
            function () {
                return this.getField('username');
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DeviceLoginComponent.prototype, "password", {
            get: /**
             * @return {?}
             */
            function () {
                return this.getField('password');
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @param {?} name
         * @return {?}
         */
        DeviceLoginComponent.prototype.getField = /**
         * @param {?} name
         * @return {?}
         */
        function (name) {
            /** @type {?} */
            var field = this.form.get(name);
            if (!field) {
                throw new Error("Internal error: missing input with [formControlName]=\"" + name + "\" in html template");
            }
            return field;
        };
        /**
         * @return {?}
         */
        DeviceLoginComponent.prototype.ngOnInit = /**
         * @return {?}
         */
        function () {
            var _this = this;
            this.sessionState$ = this.tap.auth.sessionState;
            this.connectionStateSub = this.tapService.connectionState.subscribe((/**
             * @param {?} event
             * @return {?}
             */
            function (event) {
                if (event.newState === api.ConnectionState.CONNECTED) {
                    if (_this.pendingLoginCall) {
                        _this._execCall(_this.pendingLoginCall);
                    }
                }
            }));
            // this.unregisterBackAction = this.platform.registerBackButtonAction(() => {
            //   this.dismiss();
            // })
        };
        // ngOnDestroy() {
        //   // if (this.unregisterBackAction) this.unregisterBackAction();
        // }
        // ngOnDestroy() {
        //   // if (this.unregisterBackAction) this.unregisterBackAction();
        // }
        /**
         * @return {?}
         */
        DeviceLoginComponent.prototype.login = 
        // ngOnDestroy() {
        //   // if (this.unregisterBackAction) this.unregisterBackAction();
        // }
        /**
         * @return {?}
         */
        function () {
            return __awaiter(this, void 0, void 0, function () {
                var username, password, rememberMe, autoLogin, options, loginCall;
                var _this = this;
                return __generator(this, function (_a) {
                    this.loading = true;
                    username = this.username.value;
                    password = this.password.value;
                    rememberMe = this.rememberMe.value;
                    autoLogin = this.autoLogin.value;
                    options = { username: username, password: password, rememberMe: rememberMe, autoLogin: autoLogin };
                    loginCall = (/**
                     * @return {?}
                     */
                    function () { return __awaiter(_this, void 0, void 0, function () {
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, this.tapService.login(username, password, this.refreshSessionState)];
                                case 1:
                                    _a.sent();
                                    return [2 /*return*/, options];
                            }
                        });
                    }); });
                    this._execCall(loginCall);
                    return [2 /*return*/];
                });
            });
        };
        /**
         * @return {?}
         */
        DeviceLoginComponent.prototype.dismiss = /**
         * @return {?}
         */
        function () {
            return __awaiter(this, void 0, void 0, function () {
                var topOverlay;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.modalController.getTop()];
                        case 1:
                            topOverlay = _a.sent();
                            if (topOverlay) {
                                this.modalController.dismiss(topOverlay.id);
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * @return {?}
         */
        DeviceLoginComponent.prototype.cancelAction = /**
         * @return {?}
         */
        function () {
            this.pendingLoginCall = undefined;
            this.error = undefined;
            this.form.enable();
        };
        /**
         * @private
         * @param {?} call
         * @return {?}
         */
        DeviceLoginComponent.prototype._execCall = /**
         * @private
         * @param {?} call
         * @return {?}
         */
        function (call) {
            var _this = this;
            this.loading = true;
            return call()
                .then((/**
             * @param {?} options
             * @return {?}
             */
            function (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) {
                    _this.router.navigateByUrl(_this.returnUrl);
                }
                _this.pendingLoginCall = undefined;
                _this.form.enable();
                _this.dismiss();
            }))
                .catch((/**
             * @param {?} err
             * @return {?}
             */
            function (err) {
                if (err.code === impl.TapClientError.Code.NotConnectedError
                    || err.code === 'NfcTagLostError'
                    || err.code === 'NfcNotConnectedError') {
                    _this.pendingLoginCall = call;
                    _this.form.disable();
                }
                else {
                    _this._onError(err);
                }
            }))
                .then((/**
             * @return {?}
             */
            function () {
                _this.loading = false;
            }));
        };
        /**
         * @private
         * @param {?} err
         * @return {?}
         */
        DeviceLoginComponent.prototype._onError = /**
         * @private
         * @param {?} err
         * @return {?}
         */
        function (err) {
            this.error = err;
            this.onError.emit(err);
        };
        DeviceLoginComponent.decorators = [
            { type: core.Component, args: [{
                        selector: 'tap-device-login',
                        template: "<ion-header *ngIf=\"header\">\r\n    <ion-toolbar color=\"primary\">\r\n        <ion-buttons slot=\"start\">\r\n            <ion-back-button *ngIf=\"backButton\" [defaultHref]=\"'/device'\"></ion-back-button>\r\n            <ion-button *ngIf=\"closeButton\" (click)=\"dismiss()\">\r\n                <ion-icon name=\"arrow-back\"></ion-icon>\r\n            </ion-button>\r\n        </ion-buttons>\r\n        <ion-title class=\"text-center\">\r\n            {{title}}\r\n        </ion-title>\r\n    </ion-toolbar>\r\n</ion-header>\r\n<ion-content>\r\n    <ion-progress-bar type=\"indeterminate\" [hidden]=\"!loading\"></ion-progress-bar>\r\n    <ion-grid>\r\n        <ion-row>\r\n            <ion-col class=\"ion-align-self-center\">\r\n                <iotize-feedback-error [error]=\"error\"></iotize-feedback-error>\r\n                <form (ngSubmit)=\"login()\" [formGroup]=\"form\" (keydown.enter)=\"login()\">\r\n                    <div class=\"ion-padding\">\r\n                        <ion-item>\r\n                            <ion-input type=\"text\" [formControlName]=\"'username'\" placeholder=\"Username\"></ion-input>\r\n                        </ion-item>\r\n                        <ion-item>\r\n                            <ion-input type=\"password\" [formControlName]=\"'password'\" placeholder=\"Password\"></ion-input>\r\n                        </ion-item>\r\n                        <ion-item *ngIf=\"enableRememberMe\">\r\n                            <ion-label>Remember me</ion-label>\r\n                            <ion-toggle [formControlName]=\"'rememberMe'\"></ion-toggle>\r\n                        </ion-item>\r\n                        <ion-item *ngIf=\"rememberMe.value && enableAutoLogin\">\r\n                            <ion-label>Automatic login on connection</ion-label>\r\n                            <ion-toggle [formControlName]=\"'autoLogin'\"></ion-toggle>\r\n                        </ion-item>\r\n                    </div>\r\n                    <ion-item lines=\"none\">\r\n                        <ion-button *ngIf=\"pendingLoginCall\" slot=\"end\" (click)=\"cancelAction()\" color=\"warning\" size=\"default\">\r\n                            <ion-icon name=\"close\"></ion-icon>\r\n                            Cancel\r\n                        </ion-button>\r\n                        <ion-button slot=\"end\" type=\"submit\" [disabled]=\"loading || pendingLoginCall\" size=\"default\">\r\n                            <ion-icon name=\"log-in\"></ion-icon>\r\n                            Login\r\n                        </ion-button>\r\n                    </ion-item>\r\n                    <ion-item lines=\"none\" *ngIf=\"pendingLoginCall\">\r\n                        <ion-text class=\"ion-text-wrap\" slot=\"end\" color=\"warning\">\r\n                            <ion-icon name=\"alert\"></ion-icon>\r\n                            Please reconnect Tap to login\r\n                        </ion-text>\r\n                    </ion-item>\r\n                </form>\r\n            </ion-col>\r\n        </ion-row>\r\n    </ion-grid>\r\n</ion-content>\r\n<ion-footer *ngIf=\"footer\"></ion-footer>\r\n",
                        styles: ["ion-grid{height:100%;justify-content:center}"]
                    }] }
        ];
        /** @nocollapse */
        DeviceLoginComponent.ctorParameters = function () { return [
            { type: ionic.CurrentDeviceService },
            { type: router.Router },
            { type: angular.Platform },
            { type: angular.ModalController },
            { type: forms.FormBuilder },
            { type: TapAuthService }
        ]; };
        DeviceLoginComponent.propDecorators = {
            refreshSessionState: [{ type: core.Input }],
            header: [{ type: core.Input }],
            footer: [{ type: core.Input }],
            returnUrl: [{ type: core.Input }],
            closeButton: [{ type: core.Input }],
            backButton: [{ type: core.Input }],
            enableAutoLogin: [{ type: core.Input }],
            enableRememberMe: [{ type: core.Input }],
            title: [{ type: core.Input }],
            onError: [{ type: core.Output }]
        };
        return DeviceLoginComponent;
    }());
    if (false) {
        /**
         * Refresh session state on login
         * @type {?}
         */
        DeviceLoginComponent.prototype.refreshSessionState;
        /** @type {?} */
        DeviceLoginComponent.prototype.header;
        /** @type {?} */
        DeviceLoginComponent.prototype.footer;
        /** @type {?} */
        DeviceLoginComponent.prototype.returnUrl;
        /** @type {?} */
        DeviceLoginComponent.prototype.closeButton;
        /** @type {?} */
        DeviceLoginComponent.prototype.backButton;
        /** @type {?} */
        DeviceLoginComponent.prototype.enableAutoLogin;
        /** @type {?} */
        DeviceLoginComponent.prototype.enableRememberMe;
        /** @type {?} */
        DeviceLoginComponent.prototype.title;
        /** @type {?} */
        DeviceLoginComponent.prototype.onError;
        /** @type {?} */
        DeviceLoginComponent.prototype.form;
        /** @type {?} */
        DeviceLoginComponent.prototype.error;
        /** @type {?} */
        DeviceLoginComponent.prototype.sessionState$;
        /** @type {?} */
        DeviceLoginComponent.prototype.promise$;
        /** @type {?} */
        DeviceLoginComponent.prototype.loading;
        /** @type {?} */
        DeviceLoginComponent.prototype.pendingLoginCall;
        /** @type {?} */
        DeviceLoginComponent.prototype.connectionStateSub;
        /**
         * @type {?}
         * @protected
         */
        DeviceLoginComponent.prototype.tapService;
        /**
         * @type {?}
         * @private
         */
        DeviceLoginComponent.prototype.router;
        /**
         * @type {?}
         * @private
         */
        DeviceLoginComponent.prototype.platform;
        /** @type {?} */
        DeviceLoginComponent.prototype.modalController;
        /**
         * @type {?}
         * @private
         */
        DeviceLoginComponent.prototype.formBuilder;
        /**
         * @type {?}
         * @private
         */
        DeviceLoginComponent.prototype.tapAuth;
    }

    /**
     * @fileoverview added by tsickle
     * Generated from: lib/change-password/change-password.component.ts
     * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
     */
    /** @type {?} */
    var TASK_ID = 'change-user-password';
    var ChangePasswordComponent = /** @class */ (function () {
        function ChangePasswordComponent(currentDevice, modalController, formBuilder, taskManager) {
            var _this = this;
            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: ['', forms.Validators.required],
                confirmPassword: [''],
                currentPassword: [''],
            });
            this.changePasswordTask = this.taskManager.createTask({
                id: TASK_ID,
                info: {
                    title: 'Change user password',
                    feedback: 'User password changed!'
                },
                exec: (/**
                 * @return {?}
                 */
                function () {
                    return _this.changePassword();
                })
            });
        }
        Object.defineProperty(ChangePasswordComponent.prototype, "tap", {
            get: /**
             * @return {?}
             */
            function () {
                return this.currentDevice.tap;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ChangePasswordComponent.prototype, "password", {
            get: /**
             * @return {?}
             */
            function () {
                return (/** @type {?} */ (this.form.get('password')));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ChangePasswordComponent.prototype, "currentPassword", {
            get: /**
             * @return {?}
             */
            function () {
                return (/** @type {?} */ (this.form.get('currentPassword')));
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @return {?}
         */
        ChangePasswordComponent.prototype.ngOnInit = /**
         * @return {?}
         */
        function () {
        };
        /**
         * @return {?}
         */
        ChangePasswordComponent.prototype.submit = /**
         * @return {?}
         */
        function () {
            this.error = undefined;
            this.changePasswordTaskComponent.execTask();
        };
        /**
         * @return {?}
         */
        ChangePasswordComponent.prototype.changePassword = /**
         * @return {?}
         */
        function () {
            return __awaiter(this, void 0, void 0, function () {
                var newPassword, err_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 4, , 5]);
                            newPassword = this.password.value;
                            if (!this.askCurrentPassword) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.tap.auth.login({
                                    username: this.tap.auth.sessionStateSnapshot.name,
                                    password: this.currentPassword.value
                                })];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            this.promise$ = this.tap.auth.changePassword(newPassword, this.userId);
                            return [4 /*yield*/, this.promise$];
                        case 3:
                            _a.sent();
                            this.modalController.dismiss();
                            return [3 /*break*/, 5];
                        case 4:
                            err_1 = _a.sent();
                            this.showError(err_1);
                            return [3 /*break*/, 5];
                        case 5: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * @return {?}
         */
        ChangePasswordComponent.prototype.dismiss = /**
         * @return {?}
         */
        function () {
            this.modalController.dismiss();
        };
        /**
         * @param {?} err
         * @return {?}
         */
        ChangePasswordComponent.prototype.showError = /**
         * @param {?} err
         * @return {?}
         */
        function (err) {
            this.error = err;
        };
        ChangePasswordComponent.decorators = [
            { type: core.Component, args: [{
                        selector: 'tap-change-password',
                        template: "<ion-header *ngIf=\"header\">\r\n\t<ion-toolbar color=\"primary\">\r\n\t\t<ion-buttons slot=\"start\">\r\n\t\t\t<ion-button (click)=\"modalController.dismiss()\">\r\n\t\t\t  <ion-icon name=\"arrow-back\"></ion-icon>\r\n\t\t\t</ion-button>\r\n\t\t</ion-buttons>\r\n\t\t<ion-title class=\"text-center\">\r\n\t\t\tChange profile password\r\n\t\t</ion-title>\r\n\t</ion-toolbar>\r\n</ion-header>\r\n<ion-content>\r\n\t<ion-grid>\r\n\t\t<ion-row>\r\n\t\t\t<ion-col class=\"ion-align-self-center\">\r\n\t\t\t\t<iotize-feedback-error [error]=\"error\"></iotize-feedback-error>\r\n\t\t\t\t<form (ngSubmit)=\"submit()\" [formGroup]=\"form\" (keydown.enter)=\"submit()\">\r\n\t\t\t\t\t<ion-item *ngIf=\"askCurrentPassword\">\r\n\t\t\t\t\t\t<ion-input [formControlName]=\"'currentPassword'\" placeholder=\"Current password\" required type=\"password\"></ion-input>\r\n\t\t\t\t\t</ion-item>\r\n\t\t\t\t\t<ion-item>\r\n\t\t\t\t\t\t<ion-input [formControlName]=\"'password'\" placeholder=\"New password\" required type=\"password\"></ion-input>\r\n\t\t\t\t\t</ion-item>\r\n\t\t\t\t\t<ion-item *ngIf=\"confirmPassword\">\r\n\t\t\t\t\t\t<ion-input [formControlName]=\"'confirmPassword'\" placeholder=\"Confirm new password\" required type=\"password\"></ion-input>\r\n\t\t\t\t\t</ion-item>\r\n\t\t\t\t\t<app-task-manager #changePasswordTaskComponent [task]=\"changePasswordTask\">\r\n\t\t\t\t\t\t<app-task-manager-action>\r\n\t\t\t\t\t\t\t<ion-item lines=\"none\">\r\n\t\t\t\t\t\t\t\t<ion-button size=\"default\" slot=\"end\" [disabled]=\"form['invalid']\" expand=\"block\" type=\"submit\">\r\n\t\t\t\t\t\t\t\t\t<ion-icon name=\"create\"></ion-icon>\r\n\t\t\t\t\t\t\t\t\tChange password\r\n\t\t\t\t\t\t\t\t</ion-button>\r\n\t\t\t\t\t\t\t</ion-item>\r\n\t\t\t\t\t\t</app-task-manager-action>\r\n\t\t\t\t\t\t<app-task-manager-delayed>\r\n\t\t\t\t\t\t\t<ion-item lines=\"none\">\r\n\t\t\t\t\t\t\t\t<ion-text class=\"ion-text-wrap\" slot=\"end\" color=\"warning\">\r\n\t\t\t\t\t\t\t\t\t<ion-icon name=\"alert\"></ion-icon>\r\n\t\t\t\t\t\t\t\t\tPlease reconnect Tap to change password\r\n\t\t\t\t\t\t\t\t</ion-text>\r\n\t\t\t\t\t\t\t\t<ion-button size=\"default\" color=\"warning\" app-task-manager-action-cancel>\r\n\t\t\t\t\t\t\t\t\t<ion-icon name=\"close\"></ion-icon>\r\n\t\t\t\t\t\t\t\t\tCancel\r\n\t\t\t\t\t\t\t\t</ion-button>\r\n\t\t\t\t\t\t\t</ion-item>\r\n\t\t\t\t\t\t</app-task-manager-delayed>\r\n\t\t\t\t\t\t<app-task-manager-running>\r\n\t\t\t\t\t\t\t<ion-item lines=\"none\">\r\n\t\t\t\t\t\t\t\t<ion-progress-bar type=\"indeterminate\"></ion-progress-bar>\r\n\t\t\t\t\t\t\t</ion-item>\r\n\t\t\t\t\t\t</app-task-manager-running>\r\n\t\t\t\t\t</app-task-manager>\r\n\t\t\t\t</form>\r\n\t\t\t</ion-col>\r\n\t\t</ion-row>\r\n\t</ion-grid>\r\n</ion-content>\r\n",
                        styles: [""]
                    }] }
        ];
        /** @nocollapse */
        ChangePasswordComponent.ctorParameters = function () { return [
            { type: ionic.CurrentDeviceService },
            { type: angular.ModalController },
            { type: forms.FormBuilder },
            { type: ionic.TaskManagerService }
        ]; };
        ChangePasswordComponent.propDecorators = {
            changePasswordTaskComponent: [{ type: core.ViewChild, args: ['changePasswordTaskComponent', { static: true },] }],
            confirmPassword: [{ type: core.Input }],
            askCurrentPassword: [{ type: core.Input }],
            header: [{ type: core.Input }],
            userId: [{ type: core.Input }]
        };
        return ChangePasswordComponent;
    }());
    if (false) {
        /** @type {?} */
        ChangePasswordComponent.prototype.changePasswordTaskComponent;
        /** @type {?} */
        ChangePasswordComponent.prototype.confirmPassword;
        /** @type {?} */
        ChangePasswordComponent.prototype.askCurrentPassword;
        /** @type {?} */
        ChangePasswordComponent.prototype.header;
        /** @type {?} */
        ChangePasswordComponent.prototype.userId;
        /** @type {?} */
        ChangePasswordComponent.prototype.form;
        /** @type {?} */
        ChangePasswordComponent.prototype.promise$;
        /** @type {?} */
        ChangePasswordComponent.prototype.error;
        /** @type {?} */
        ChangePasswordComponent.prototype.loading;
        /** @type {?} */
        ChangePasswordComponent.prototype.changePasswordTask;
        /**
         * @type {?}
         * @protected
         */
        ChangePasswordComponent.prototype.currentDevice;
        /** @type {?} */
        ChangePasswordComponent.prototype.modalController;
        /**
         * @type {?}
         * @private
         */
        ChangePasswordComponent.prototype.formBuilder;
        /**
         * @type {?}
         * @private
         */
        ChangePasswordComponent.prototype.taskManager;
    }

    /**
     * @fileoverview added by tsickle
     * Generated from: lib/debug.ts
     * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
     */
    /** @type {?} */
    var debug = debug$1.createDebugger('@iotize/ionic:auth');

    /**
     * @fileoverview added by tsickle
     * Generated from: lib/device-auth.guard.ts
     * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
     */
    /** @type {?} */
    var DEVICE_AUTH_GUARD_CONFIG = new core.InjectionToken('DEVICE_AUTH_GUARD_CONFIG');
    /**
     * @record
     */
    function DeviceAuthGuardRouteData() { }
    if (false) {
        /** @type {?|undefined} */
        DeviceAuthGuardRouteData.prototype.disableAuthGuardOnPage;
        /** @type {?|undefined} */
        DeviceAuthGuardRouteData.prototype.username;
    }
    /**
     * @record
     */
    function DeviceAuthGuardConfig() { }
    if (false) {
        /** @type {?} */
        DeviceAuthGuardConfig.prototype.loginUrl;
    }
    var DeviceAuthGuard = /** @class */ (function () {
        // private routerData?: DeviceAuthGuardRouteData;
        function DeviceAuthGuard(tapService, router, route, config) {
            this.tapService = tapService;
            this.router = router;
            this.route = route;
            this.config = config;
            this.subscriptions = {};
            // this.setupSessionStateListener();
        }
        /**
         * @param {?} component
         * @param {?} currentRoute
         * @param {?} currentState
         * @param {?=} nextState
         * @return {?}
         */
        DeviceAuthGuard.prototype.canDeactivate = /**
         * @param {?} component
         * @param {?} currentRoute
         * @param {?} currentState
         * @param {?=} nextState
         * @return {?}
         */
        function (component, currentRoute, currentState, nextState) {
            // if (this.sessionStateSub) {
            //   this.sessionStateSub.unsubscribe();
            // }
            return true;
        };
        /**
         * @param {?} route
         * @param {?} state
         * @return {?}
         */
        DeviceAuthGuard.prototype.canActivate = /**
         * @param {?} route
         * @param {?} state
         * @return {?}
         */
        function (route, state) {
            var _this = this;
            this.setupSessionStateListener(route, state);
            if (!route.data.username) {
                return rxjs.of(true);
            }
            debug("Check is login as \"" + route.data.username + "\" to access \"" + route.url + "\"");
            return rxjs.from(this.tapService
                .isLoggedInAs(route.data.username))
                .pipe(operators.map((/**
             * @param {?} isLoggedAs
             * @return {?}
             */
            function (isLoggedAs) {
                if (!isLoggedAs) {
                    _this.onUnauthorized(state.url, route);
                }
                return isLoggedAs;
            })));
        };
        /**
         * @private
         * @param {?} returnUrl
         * @param {?} activatedRoute
         * @return {?}
         */
        DeviceAuthGuard.prototype.onUnauthorized = /**
         * @private
         * @param {?} returnUrl
         * @param {?} activatedRoute
         * @return {?}
         */
        function (returnUrl, activatedRoute) {
            debug("Not authorized to access this route \"" + activatedRoute.url + "\" -> redirect to \"" + this.config.loginUrl + "\"");
            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
         * @param state
         */
        /**
         * Listen to session state changes for the given route. It it's the active route, we redirect to login
         * @param {?} activatedRoute
         * @param {?} state
         * @return {?}
         */
        DeviceAuthGuard.prototype.setupSessionStateListener = /**
         * Listen to session state changes for the given route. It it's the active route, we redirect to login
         * @param {?} activatedRoute
         * @param {?} state
         * @return {?}
         */
        function (activatedRoute, state) {
            var _this = this;
            if (state.url in this.subscriptions) {
                return this.subscriptions[state.url];
            }
            /** @type {?} */
            var subscription = this.tapService
                .sessionState
                .subscribe((/**
             * @param {?} event
             * @return {?}
             */
            function (event) {
                if (_this.router.isActive(state.url, true)) {
                    /** @type {?} */
                    var routeData = activatedRoute.data;
                    if (routeData && routeData.username && !routeData.disableAuthGuardOnPage) {
                        /** @type {?} */
                        var 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) {
                            _this.onUnauthorized(state.url, activatedRoute);
                        }
                    }
                }
            }));
            this.subscriptions[state.url] = subscription;
            return subscription;
        };
        DeviceAuthGuard.decorators = [
            { type: core.Injectable, args: [{
                        providedIn: 'root'
                    },] }
        ];
        /** @nocollapse */
        DeviceAuthGuard.ctorParameters = function () { return [
            { type: ionic.CurrentDeviceService },
            { type: router.Router },
            { type: router.ActivatedRoute },
            { type: undefined, decorators: [{ type: core.Inject, args: [DEVICE_AUTH_GUARD_CONFIG,] }] }
        ]; };
        /** @nocollapse */ DeviceAuthGuard.ɵprov = core.ɵɵdefineInjectable({ factory: function DeviceAuthGuard_Factory() { return new DeviceAuthGuard(core.ɵɵinject(ionic.CurrentDeviceService), core.ɵɵinject(router.Router), core.ɵɵinject(router.ActivatedRoute), core.ɵɵinject(DEVICE_AUTH_GUARD_CONFIG)); }, token: DeviceAuthGuard, providedIn: "root" });
        return DeviceAuthGuard;
    }());
    if (false) {
        /**
         * @type {?}
         * @private
         */
        DeviceAuthGuard.prototype.subscriptions;
        /**
         * @type {?}
         * @private
         */
        DeviceAuthGuard.prototype.tapService;
        /**
         * @type {?}
         * @private
         */
        DeviceAuthGuard.prototype.router;
        /**
         * @type {?}
         * @private
         */
        DeviceAuthGuard.prototype.route;
        /** @type {?} */
        DeviceAuthGuard.prototype.config;
    }

    /**
     * @fileoverview added by tsickle
     * Generated from: lib/tap-auth.module.ts
     * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
     */
    var TapAuthModule = /** @class */ (function () {
        function TapAuthModule() {
        }
        TapAuthModule.decorators = [
            { type: core.NgModule, args: [{
                        declarations: [
                            DeviceLoginComponent,
                            ChangePasswordComponent
                        ],
                        exports: [
                            DeviceLoginComponent,
                            ChangePasswordComponent,
                        ],
                        providers: [
                            DeviceAuthGuard
                        ],
                        entryComponents: [
                            DeviceLoginComponent,
                            ChangePasswordComponent
                        ],
                        imports: [
                            ionic.LibCommonModule,
                            forms.FormsModule,
                            forms.ReactiveFormsModule,
                            ionic.TaskManagerUiModule
                        ]
                    },] }
        ];
        return TapAuthModule;
    }());

    exports.ChangePasswordComponent = ChangePasswordComponent;
    exports.DEVICE_AUTH_GUARD_CONFIG = DEVICE_AUTH_GUARD_CONFIG;
    exports.DeviceAuthGuard = DeviceAuthGuard;
    exports.DeviceLoginComponent = DeviceLoginComponent;
    exports.TapAuthModule = TapAuthModule;
    exports.TapAuthService = TapAuthService;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=iotize-ionic-auth.umd.js.map
