import { HTTP_INTERCEPTORS } from '@angular/common/http';
import * as i0 from '@angular/core';
import { Injectable, Component, ViewChild, NgModule } from '@angular/core';
import { AppVersion } from '@awesome-cordova-plugins/app-version/ngx';
import { BarcodeScanner } from '@awesome-cordova-plugins/barcode-scanner/ngx';
import { Calendar } from '@awesome-cordova-plugins/calendar/ngx';
import { Camera } from '@awesome-cordova-plugins/camera/ngx';
import * as i2 from '@awesome-cordova-plugins/file/ngx';
import { File } from '@awesome-cordova-plugins/file/ngx';
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
import { Device } from '@awesome-cordova-plugins/device/ngx';
import { MediaCapture } from '@awesome-cordova-plugins/media-capture/ngx';
import { Geolocation } from '@awesome-cordova-plugins/geolocation/ngx';
import { Network } from '@awesome-cordova-plugins/network/ngx';
import { SQLite } from '@awesome-cordova-plugins/sqlite/ngx';
import { Vibration } from '@awesome-cordova-plugins/vibration/ngx';
import { LocationAccuracy } from '@awesome-cordova-plugins/location-accuracy/ngx';
import { Diagnostic } from '@awesome-cordova-plugins/diagnostic/ngx';
import * as i1$1 from '@wm/core';
import { isIos, hasCordova, getWmProjectProperties, executePromiseChain, removeExtraSlashes, loadStyleSheet, insertAfter, removeNode, loadScript } from '@wm/core';
import { forEach, split, keys } from 'lodash-es';
import { FileExtensionFromMimePipe } from '@wm/components/base';
import * as i3 from '@wm/mobile/core';
import { MobileCoreModule } from '@wm/mobile/core';
import { OfflineModule, PushService, PushServiceImpl } from '@wm/mobile/offline';
import * as i4 from '@wm/security';
import { VariablesModule } from '@wm/mobile/variables';
import { CONSTANTS, $rootScope } from '@wm/variables';
import * as i1 from '@wm/mobile/components/basic';
import { FileBrowserComponent, ProcessManagerComponent, BasicModule } from '@wm/mobile/components/basic';
import { Subject, from } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { SearchModule } from '@wm/mobile/components/basic/search';
import { SegmentedControlModule } from '@wm/mobile/components/containers/segmented-control';
import { MediaListModule } from '@wm/mobile/components/data/media-list';
import { BarcodeScannerModule } from '@wm/mobile/components/device/barcode-scanner';
import { CameraModule } from '@wm/mobile/components/device/camera';
import { FileUploadModule } from '@wm/mobile/components/input/file-upload';
import { PageModule } from '@wm/mobile/components/page';
import { LeftPanelModule } from '@wm/mobile/components/page/left-panel';
import { MobileNavbarModule } from '@wm/mobile/components/page/mobile-navbar';
import { TabBarModule } from '@wm/mobile/components/page/tab-bar';

const STORAGE_KEY = 'wavemaker.persistedcookies';
class CookieService {
    constructor() {
        this.cookieInfo = {};
        this.serviceName = 'CookeService';
    }
    static { this.SERVICE_NAME = 'CookieService'; }
    persistCookie(hostname, cookieName, cookieValue) {
        return new Promise((resolve, reject) => {
            if (cookieValue) {
                resolve(cookieValue);
            }
            else {
                this.getCookie(hostname, cookieName)
                    .then(data => resolve(data.cookieValue), reject);
            }
        }).then(value => {
            this.cookieInfo[hostname + '-' + cookieName] = {
                hostname: hostname.replace(/:[0-9]+/, ''),
                name: cookieName,
                value: this.rotateLTR(value)
            };
            localStorage.setItem(STORAGE_KEY, JSON.stringify(this.cookieInfo));
        });
    }
    getCookie(hostname, cookieName) {
        return new Promise((resolve, reject) => {
            if (isIos()) {
                const cookieString = window['cordova'].plugin.http.getCookieString(hostname);
                if (cookieString) {
                    const at = cookieString.indexOf(cookieName);
                    if (at >= 0) {
                        const start = at + cookieName.length + 1;
                        const end = cookieString.indexOf(';', start);
                        const cookieValue = cookieString.substring(start, end >= 0 ? end : undefined);
                        resolve({
                            cookieValue: cookieValue
                        });
                        return;
                    }
                }
                reject();
            }
            else {
                window['cookieEmperor'].getCookie(hostname, cookieName, resolve, reject);
            }
        });
    }
    setCookie(hostname, cookieName, cookieValue) {
        return new Promise((resolve, reject) => {
            if (isIos()) {
                const cookieString = cookieName + '=' + cookieValue;
                window['cordova'].plugin.http.setCookie(hostname, cookieString);
                resolve();
            }
            else {
                window['cookieEmperor'].setCookie(hostname, cookieName, cookieValue, resolve, reject);
            }
        });
    }
    clearAll() {
        return new Promise((resolve, reject) => {
            if (isIos()) {
                window['cordova'].plugin.http.clearCookies();
                resolve('');
            }
            else {
                window['cookieEmperor'].clearAll(resolve, reject);
            }
        });
    }
    /**
     * Loads persisted cookies from local storage and adds them to the browser.
     * @returns {*}
     */
    start() {
        const cookieInfoStr = localStorage.getItem(STORAGE_KEY), promises = [];
        if (cookieInfoStr) {
            const cookieInfo = JSON.parse(cookieInfoStr);
            forEach(cookieInfo, c => {
                // @ts-ignore
                if (c.name && c.value) {
                    // @ts-ignore
                    promises.push(this.getCookie(c.hostname, c.name).catch(() => {
                        return new Promise((resolve, reject) => {
                            // @ts-ignore
                            window['cookieEmperor'].setCookie(c.hostname, c.name, this.rotateRTL(c.value), resolve, reject);
                        });
                    }));
                }
            });
        }
        return Promise.all(promises);
    }
    getServiceName() {
        return CookieService.SERVICE_NAME;
    }
    /**
     * Just rotates the given string exactly from 1/3 of string length in left to right direction.
     * @param str
     * @returns {string}
     */
    rotateLTR(str) {
        const arr = str.split(''), tArr = [], shift = Math.floor(str.length / 3);
        arr.forEach((v, i) => {
            tArr[(i + shift) % arr.length] = arr[i];
        });
        return tArr.join('');
    }
    /**
     * Just rotates the given string exactly from 1/3 of string length in  right to left direction..
     * @param str
     * @returns {string}
     */
    rotateRTL(str) {
        const arr = str.split(''), tArr = [], shift = Math.floor(str.length / 3);
        arr.forEach((v, i) => {
            tArr[(arr.length + i - shift) % arr.length] = arr[i];
        });
        return tArr.join('');
    }
    static { this.ɵfac = function CookieService_Factory(t) { return new (t || CookieService)(); }; }
    static { this.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: CookieService, factory: CookieService.ɵfac, providedIn: 'root' }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(CookieService, [{
        type: Injectable,
        args: [{
                providedIn: 'root'
            }]
    }], null, null); })();

const _c0 = ["wmAppExt", ""];
class AppExtComponent {
    constructor(elRef, fileSelectorService, processManagementService) {
        this.elRef = elRef;
        this.fileSelectorService = fileSelectorService;
        this.processManagementService = processManagementService;
    }
    ngAfterViewInit() {
        const mobileElements = $(this.elRef.nativeElement).find('>[wmNetworkInfoToaster], >[wmAppUpdate], >[wmMobileFileBrowser]');
        const $body = $('body');
        if (hasCordova()) {
            mobileElements.appendTo($body);
            this.fileSelectorService.setFileBrowser(this.fileBrowserComponent);
        }
        else {
            mobileElements.remove();
        }
        $(this.elRef.nativeElement).find('>[wmProgressManager]').appendTo($body);
        this.processManagementService.setUIComponent(this.processManagerComponent);
    }
    static { this.ɵfac = function AppExtComponent_Factory(t) { return new (t || AppExtComponent)(i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i1.FileSelectorService), i0.ɵɵdirectiveInject(i1.ProcessManagementService)); }; }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: AppExtComponent, selectors: [["", "wmAppExt", ""]], viewQuery: function AppExtComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(FileBrowserComponent, 5);
            i0.ɵɵviewQuery(ProcessManagerComponent, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.fileBrowserComponent = _t.first);
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.processManagerComponent = _t.first);
        } }, attrs: _c0, decls: 5, vars: 0, consts: [["wmNetworkInfoToaster", ""], ["wmAppUpdate", ""], ["wmMobileFileBrowser", ""], ["wmProcessManager", ""]], template: function AppExtComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementContainerStart(0);
            i0.ɵɵelement(1, "div", 0)(2, "div", 1)(3, "div", 2)(4, "div", 3);
            i0.ɵɵelementContainerEnd();
        } }, dependencies: [i1.AppUpdateComponent, i1.FileBrowserComponent, i1.NetworkInfoToasterComponent, i1.ProcessManagerComponent], encapsulation: 2 }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(AppExtComponent, [{
        type: Component,
        args: [{
                selector: '[wmAppExt]',
                template: `<ng-container> 
        <div wmNetworkInfoToaster></div>
        <div wmAppUpdate></div>
        <div wmMobileFileBrowser></div>
        <div wmProcessManager></div>
    </ng-container>`
            }]
    }], () => [{ type: i0.ElementRef }, { type: i1.FileSelectorService }, { type: i1.ProcessManagementService }], { fileBrowserComponent: [{
            type: ViewChild,
            args: [FileBrowserComponent]
        }], processManagerComponent: [{
            type: ViewChild,
            args: [ProcessManagerComponent]
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(AppExtComponent, { className: "AppExtComponent", filePath: "components/app-ext.component.ts", lineNumber: 15 }); })();

class MobileHttpInterceptor {
    constructor(app, file, deviceFileDownloadService, deviceService, networkService, securityService) {
        this.app = app;
        this.deviceService = deviceService;
        this.networkService = networkService;
        this.requestInterceptors = [];
        if (hasCordova()) {
            this.requestInterceptors.push(new SecurityInterceptor(app, file, securityService));
            this.requestInterceptors.push(new ServiceCallInterceptor(app));
        }
    }
    intercept(request, next) {
        const subject = new Subject();
        const token = localStorage.getItem(CONSTANTS.XSRF_COOKIE_NAME);
        const xsrfHeaderName = getWmProjectProperties().xsrf_header_name;
        if (token
            && xsrfHeaderName
            && this.app.deployedUrl
            && (request.url.indexOf('://') < 0
                || request.url.startsWith(this.app.deployedUrl))) {
            // Clone the request to add the new header
            request = request.clone({ headers: request.headers.set(xsrfHeaderName, token) });
        }
        const data = { request: request };
        // invoke the request only when device is ready.
        const obs = from(this.deviceService.whenReady()
            .then(() => executePromiseChain(this.getInterceptors(), [data])));
        return obs.pipe(mergeMap(() => {
            return next.handle(data.request);
        }));
    }
    getInterceptors() {
        return this.requestInterceptors.map(i => {
            return (data) => i.intercept(data.request).then(req => data.request = req);
        });
    }
    onHttpError(response) {
        if (hasCordova
            && (!response || !response.status || response.status < 0 || response.status === 404)
            && (this.networkService.isConnected())) {
            this.networkService.isAvailable(true);
        }
    }
    static { this.ɵfac = function MobileHttpInterceptor_Factory(t) { return new (t || MobileHttpInterceptor)(i0.ɵɵinject(i1$1.App), i0.ɵɵinject(i2.File), i0.ɵɵinject(i3.DeviceFileDownloadService), i0.ɵɵinject(i3.DeviceService), i0.ɵɵinject(i3.NetworkService), i0.ɵɵinject(i4.SecurityService)); }; }
    static { this.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: MobileHttpInterceptor, factory: MobileHttpInterceptor.ɵfac }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(MobileHttpInterceptor, [{
        type: Injectable
    }], () => [{ type: i1$1.App }, { type: i2.File }, { type: i3.DeviceFileDownloadService }, { type: i3.DeviceService }, { type: i3.NetworkService }, { type: i4.SecurityService }], null); })();
class ServiceCallInterceptor {
    static { this.REMOTE_SERVICE_URL_PATTERNS = [
        new RegExp('^((./)|/)?services/'),
        new RegExp('j_spring_security_check'),
        new RegExp('j_spring_security_logout')
    ]; }
    constructor(app) {
        this.app = app;
    }
    intercept(request) {
        let modifiedRequest = request;
        let url = request.url;
        // if necessary, prepend deployed url
        if (url.indexOf('://') < 0
            && ServiceCallInterceptor.REMOTE_SERVICE_URL_PATTERNS.find(r => r.test(url))) {
            url = this.app.deployedUrl + url;
        }
        url = removeExtraSlashes(url);
        if (url !== request.url) {
            modifiedRequest = request.clone({
                url: url
            });
        }
        return Promise.resolve(modifiedRequest);
    }
}
class SecurityInterceptor {
    static { this.PAGE_URL_PATTERN = new RegExp('page.min.json$'); }
    static { this.PREFAB_URL_PATTERN = new RegExp('^app/prefabs/.*/page.min.json$'); }
    constructor(app, file, securityService) {
        this.app = app;
        this.file = file;
        this.securityService = securityService;
        this.initialized = false;
    }
    intercept(request) {
        return new Promise((resolve, reject) => {
            if (!SecurityInterceptor.PREFAB_URL_PATTERN.test(request.url)
                && SecurityInterceptor.PAGE_URL_PATTERN.test(request.url)) {
                return Promise.resolve().then(() => {
                    if (!this.initialized) {
                        return this.init();
                    }
                }).then(() => {
                    const urlSplits = split(request.url, '/');
                    const pageName = urlSplits[urlSplits.length - 2];
                    if (!this.publicPages || this.publicPages[pageName]) {
                        return Promise.resolve(request);
                    }
                    else {
                        this.securityService.getConfig(config => {
                            if (!config.securityEnabled || config.authenticated) {
                                resolve(request);
                            }
                            else {
                                reject(`Page '${pageName}' is not accessible to the user.`);
                                this.app.notify('http401', { page: pageName });
                            }
                        }, () => reject(`Security call failed.`));
                    }
                    return Promise.resolve(request);
                }).then(resolve, reject);
            }
            return resolve(request);
        });
    }
    /**
     * loads public pages from 'metadata/app/public-pages.info' and overrides canAccess method SecurityService
     */
    init() {
        const folderPath = cordova.file.applicationDirectory + 'www/metadata/app', fileName = 'public-pages.json';
        return this.file.readAsText(folderPath, fileName).then(text => {
            if (!this.initialized) {
                this.publicPages = {};
                this.initialized = true;
                forEach(JSON.parse(text), pageName => this.publicPages[pageName] = true);
            }
        }).catch(() => {
            this.initialized = true;
        });
    }
}

class WebProcessService {
    constructor(app, httpService, extAppMessageService) {
        this.app = app;
        this.httpService = httpService;
        this.extAppMessageService = extAppMessageService;
    }
    execute(process, hookUrl, useSystemBrowser = false) {
        return this.httpService.get(`/services/webprocess/prepare?processName=${process}&hookUrl=${hookUrl}&requestSourceType=MOBILE`)
            .then((processInfo) => {
            if (useSystemBrowser) {
                return this.executeWithSystemBrowser(processInfo);
            }
            else {
                return this.executeWithInAppBrowser(processInfo, process);
            }
        }).then(output => {
            return this.httpService.get('/services/webprocess/decode?encodedProcessdata=' + output);
        });
    }
    executeWithSystemBrowser(processInfo) {
        return new Promise((resolve) => {
            const oauthAdress = '^services/webprocess/LOGIN';
            const deregister = this.extAppMessageService.subscribe(oauthAdress, message => {
                resolve(message.data['process_output']);
                deregister();
            });
            window.open(this.app.deployedUrl + 'services/webprocess/start?process=' + encodeURIComponent(processInfo), '_system');
        });
    }
    executeWithInAppBrowser(processInfo, process) {
        return new Promise((resolve, reject) => {
            const ref = cordova.InAppBrowser.open(this.app.deployedUrl + 'services/webprocess/start?process=' + encodeURIComponent(processInfo), '_blank', 'location=yes,clearcache=yes');
            let isSuccess = false;
            ref.addEventListener('loadstop', () => {
                ref.executeScript({ code: this.getScriptToInject(process) }, output => {
                    if (output && output[0]) {
                        isSuccess = true;
                        ref.close();
                        resolve(output[0]);
                    }
                });
            });
            ref.addEventListener('exit', () => {
                if (!isSuccess) {
                    reject('Login process is stopped');
                }
            });
        });
    }
    getScriptToInject(process) {
        return `
            (function() {
                var elements = document.querySelectorAll('body.flex>a.link');
                for (var i = 0; i < elements.length; i++) {
                    var href = elements[i].href;
                    if (href && href.indexOf('://services/webprocess/${process}?process_output=')) {
                        return href.split('process_output=')[1];
                    }
                }
                window.isWebLoginProcess = true;
            })();
        `;
    }
    static { this.ɵfac = function WebProcessService_Factory(t) { return new (t || WebProcessService)(i0.ɵɵinject(i1$1.App), i0.ɵɵinject(i1$1.AbstractHttpService), i0.ɵɵinject(i3.ExtAppMessageService)); }; }
    static { this.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: WebProcessService, factory: WebProcessService.ɵfac }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(WebProcessService, [{
        type: Injectable
    }], () => [{ type: i1$1.App }, { type: i1$1.AbstractHttpService }, { type: i3.ExtAppMessageService }], null); })();

const MAX_WAIT_TIME_4_OAUTH_MESSAGE = 60000;
const MINIMUM_TAB_WIDTH = 768;
const KEYBOARD_CLASS = 'keyboard';
const cordovaServices = [
    AppVersion,
    BarcodeScanner,
    Calendar,
    Camera,
    File,
    FileOpener,
    Device,
    Geolocation,
    MediaCapture,
    Network,
    SQLite,
    Vibration,
    LocationAccuracy,
    Diagnostic
];
const MOBILE_COMPONENT_MODULES = [
    BasicModule,
    MobileCoreModule,
    OfflineModule,
    VariablesModule,
    SearchModule,
    SegmentedControlModule,
    MediaListModule,
    BarcodeScannerModule,
    CameraModule,
    FileUploadModule,
    PageModule,
    LeftPanelModule,
    MobileNavbarModule,
    TabBarModule
];
class MobileRuntimeModule {
    static forRoot() {
        /* add all providers that are required for mobile here. This is to simplify placeholder.*/
        return {
            ngModule: MobileRuntimeModule,
            providers: [
                WebProcessService,
                {
                    provide: HTTP_INTERCEPTORS,
                    useClass: MobileHttpInterceptor,
                    multi: true
                },
                ...cordovaServices,
                FileExtensionFromMimePipe,
                { provide: PushService, useClass: PushServiceImpl }
            ]
        };
    }
    static { this.initialized = false; }
    // Startup services have to be added only once in the app life-cycle.
    static initializeRuntime(runtimeModule, app, deviceFileOpenerService, deviceService) {
        if (this.initialized) {
            return;
        }
        this.initialized = true;
        app.deployedUrl = runtimeModule.getDeployedUrl();
        if (hasCordova()) {
            const unsubscribe = app.subscribe('pageReady', (page) => {
                navigator.splashscreen.hide();
                unsubscribe();
            });
            app.subscribe('userLoggedIn', () => {
                cordova && cordova.wavemaker.syncCookies();
            });
            runtimeModule.handleKeyBoardClass();
            app.subscribe('device-file-download', (data) => {
                deviceFileOpenerService.openRemoteFile(data.url, data.extension, data.name, data.headers).then(data.successCb, data.errorCb);
            });
            const __zone_symbol__FileReader = window['__zone_symbol__FileReader'];
            if (__zone_symbol__FileReader && __zone_symbol__FileReader.READ_CHUNK_SIZE) {
                // cordova File Reader is required. Otherwise, file operations are failing.
                window['FileReader'] = __zone_symbol__FileReader;
            }
            window.open = window['cordova']['InAppBrowser']['open'];
            runtimeModule.addAuthInBrowser();
        }
        deviceService.start();
        deviceService.whenReady().then(() => {
            if (hasCordova()) {
                runtimeModule._$appEl.addClass('cordova');
                runtimeModule.exposeOAuthService();
                // Fix for issue: ios device is not considering the background style, eventhough value is set in config.xml.
                if (window['StatusBar']) {
                    window['StatusBar'].overlaysWebView(false);
                }
            }
        });
    }
    constructor(app, cookieService, deviceFileOpenerService, deviceService, securityService, httpService, extAppMessageService, networkService, webProcessService) {
        this.app = app;
        this.cookieService = cookieService;
        this.deviceFileOpenerService = deviceFileOpenerService;
        this.deviceService = deviceService;
        this.securityService = securityService;
        this.httpService = httpService;
        this.extAppMessageService = extAppMessageService;
        this.networkService = networkService;
        this.webProcessService = webProcessService;
        this._$appEl = $('.wm-app').first();
        if (this._$appEl.width() >= MINIMUM_TAB_WIDTH) {
            app.isTabletApplicationType = true;
            this._$appEl.addClass('wm-tablet-app');
        }
        else {
            this._$appEl.addClass('wm-mobile-app');
        }
        // applying os theme on getting os details
        app.subscribe('on-viewport-details', os => {
            this.applyOSTheme(os);
        });
        MobileRuntimeModule.initializeRuntime(this, this.app, this.deviceFileOpenerService, this.deviceService);
    }
    exposeOAuthService() {
        window['OAuthInMobile'] = (providerId) => {
            return new Promise((resolve, reject) => {
                const oauthAdress = '^services/oauth/' + providerId + '$';
                const deregister = this.extAppMessageService.subscribe(oauthAdress, message => {
                    resolve(message.data['access_token']);
                    deregister();
                    clearTimeout(timerId);
                });
                const timerId = setTimeout(function () {
                    deregister();
                    reject(`Time out for oauth message after ${MAX_WAIT_TIME_4_OAUTH_MESSAGE % 1000} seconds`);
                }, MAX_WAIT_TIME_4_OAUTH_MESSAGE);
            });
        };
        const handleOpenURL = window['handleOpenURL'];
        handleOpenURL.isReady = true;
        handleOpenURL(handleOpenURL.lastURL);
    }
    applyOSTheme(os) {
        let oldStyleSheet = $('link[theme="wmtheme"][href ^="themes"][href $="/style.css"]').first();
        if (oldStyleSheet.length) {
            const themeUrl = oldStyleSheet.attr('href').replace(new RegExp('/[a-z]*/style.css$'), `/${os.toLowerCase()}/style.css`), newStyleSheet = loadStyleSheet(themeUrl, { name: 'theme', value: 'wmtheme' });
            oldStyleSheet = oldStyleSheet.length > 0 && oldStyleSheet[0];
            if (newStyleSheet && oldStyleSheet) {
                insertAfter(newStyleSheet, oldStyleSheet);
                removeNode(oldStyleSheet);
            }
        }
        // In angular development, styleSheet will point to .js files
        // In angular production, styleSheet will point to 'wm-android-styles.css' or 'wm-ios-styles.css'
        const removeTheme = os.toLowerCase() === 'android' ? 'wm-ios-styles' : 'wm-android-styles';
        let isDevBuild;
        const useTheme = 'wm-' + os.toLowerCase() + '-styles';
        let unusedStyleSheet = $('link[href *=' + removeTheme + ']').first();
        if (!unusedStyleSheet.length) {
            isDevBuild = true;
            unusedStyleSheet = $('script[src *=' + removeTheme + ']').first();
        }
        if (unusedStyleSheet.length) {
            let newStyleSheet;
            if (isDevBuild) {
                newStyleSheet = unusedStyleSheet.clone();
                newStyleSheet = newStyleSheet[0];
                newStyleSheet.src = newStyleSheet.src.replace(removeTheme, useTheme);
                loadScript(newStyleSheet.src, false);
                unusedStyleSheet = unusedStyleSheet[0];
                insertAfter(newStyleSheet, unusedStyleSheet);
                removeNode(unusedStyleSheet);
            }
            else {
                newStyleSheet = $('link[href *=' + useTheme + ']').first();
                newStyleSheet = newStyleSheet[0];
                loadStyleSheet(newStyleSheet.href, { name: 'theme', value: 'wmtheme' });
                removeNode(unusedStyleSheet[0]);
            }
        }
    }
    handleKeyBoardClass() {
        const initialScreenSize = window.innerHeight;
        // keyboard class is added when keyboard is open.
        window.addEventListener('resize', () => {
            if (window.innerHeight < initialScreenSize) {
                this._$appEl.addClass(KEYBOARD_CLASS);
            }
            else {
                this._$appEl.removeClass(KEYBOARD_CLASS);
            }
        });
    }
    getDeployedUrl() {
        let deployedUrl = $rootScope.project.deployedUrl;
        if (hasCordova()) {
            const baseUrl = $('meta[name="liveSync.deployedUrl"]').attr('value');
            const config = this.deviceService.getConfig();
            if (baseUrl) {
                deployedUrl = baseUrl;
            }
            else {
                deployedUrl = this.deviceService.getBaseUrl();
            }
            this.app.customUrlScheme = config.customUrlScheme;
        }
        if (deployedUrl !== 'NONE' && !deployedUrl.endsWith('/')) {
            deployedUrl = deployedUrl + '/';
        }
        $rootScope.project.deployedUrl = deployedUrl;
        return deployedUrl;
    }
    addAuthInBrowser() {
        let isAuthenticating = false;
        this.securityService.authInBrowser = () => {
            if (!this.networkService.isConnected()) {
                return Promise.reject('In offline, app cannot contact the server.');
            }
            if (isAuthenticating) {
                return Promise.reject('Authentication is in process.');
            }
            isAuthenticating = true;
            return this.webProcessService.execute('LOGIN', '/', true)
                .then(output => {
                output = JSON.parse(output && output.replace(/&quot;/g, "\""));
                if (output[CONSTANTS.XSRF_COOKIE_NAME]) {
                    localStorage.setItem(CONSTANTS.XSRF_COOKIE_NAME, output[CONSTANTS.XSRF_COOKIE_NAME]);
                }
                isAuthenticating = false;
                return this.cookieService.clearAll()
                    .then(() => {
                    const promises = keys(output).map(k => {
                        return this.cookieService.setCookie(this.app.deployedUrl, k, output[k]);
                    });
                    return Promise.all(promises);
                });
            })
                .then(() => this.app.notify('userLoggedIn', {}))
                .catch((e) => {
                isAuthenticating = false;
                return Promise.reject(e);
            });
        };
    }
    static { this.ɵfac = function MobileRuntimeModule_Factory(t) { return new (t || MobileRuntimeModule)(i0.ɵɵinject(i1$1.App), i0.ɵɵinject(CookieService), i0.ɵɵinject(i3.DeviceFileOpenerService), i0.ɵɵinject(i3.DeviceService), i0.ɵɵinject(i4.SecurityService), i0.ɵɵinject(i1$1.AbstractHttpService), i0.ɵɵinject(i3.ExtAppMessageService), i0.ɵɵinject(i3.NetworkService), i0.ɵɵinject(WebProcessService)); }; }
    static { this.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: MobileRuntimeModule }); }
    static { this.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [MobileCoreModule,
            VariablesModule,
            BasicModule, MOBILE_COMPONENT_MODULES, BasicModule,
            MobileCoreModule,
            OfflineModule,
            VariablesModule,
            SearchModule,
            SegmentedControlModule,
            MediaListModule,
            BarcodeScannerModule,
            CameraModule,
            FileUploadModule,
            PageModule,
            LeftPanelModule,
            MobileNavbarModule,
            TabBarModule] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(MobileRuntimeModule, [{
        type: NgModule,
        args: [{
                declarations: [
                    AppExtComponent
                ],
                exports: [
                    AppExtComponent,
                    ...MOBILE_COMPONENT_MODULES
                ],
                imports: [
                    MobileCoreModule,
                    VariablesModule,
                    BasicModule,
                    ...MOBILE_COMPONENT_MODULES
                ],
                bootstrap: []
            }]
    }], () => [{ type: i1$1.App }, { type: CookieService }, { type: i3.DeviceFileOpenerService }, { type: i3.DeviceService }, { type: i4.SecurityService }, { type: i1$1.AbstractHttpService }, { type: i3.ExtAppMessageService }, { type: i3.NetworkService }, { type: WebProcessService }], null); })();
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(MobileRuntimeModule, { declarations: [AppExtComponent], imports: [MobileCoreModule,
        VariablesModule,
        BasicModule, BasicModule,
        MobileCoreModule,
        OfflineModule,
        VariablesModule,
        SearchModule,
        SegmentedControlModule,
        MediaListModule,
        BarcodeScannerModule,
        CameraModule,
        FileUploadModule,
        PageModule,
        LeftPanelModule,
        MobileNavbarModule,
        TabBarModule], exports: [AppExtComponent, BasicModule,
        MobileCoreModule,
        OfflineModule,
        VariablesModule,
        SearchModule,
        SegmentedControlModule,
        MediaListModule,
        BarcodeScannerModule,
        CameraModule,
        FileUploadModule,
        PageModule,
        LeftPanelModule,
        MobileNavbarModule,
        TabBarModule] }); })();

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

export { AppExtComponent, CookieService, MAX_WAIT_TIME_4_OAUTH_MESSAGE, MOBILE_COMPONENT_MODULES, MobileHttpInterceptor, MobileRuntimeModule, WebProcessService };
//# sourceMappingURL=index.mjs.map
