File

src/app/app.component.ts

Implements

OnInit AfterViewInit

Metadata

Index

Properties
Methods

Constructor

constructor(telemetryService: TelemetryService, preferences: SharedPreferences, eventsBusService: EventsBusService, notificationServices: NotificationService, systemSettingsService: SystemSettingsService, codePushExperimentService: CodePushExperimentService, deviceRegisterService: DeviceRegisterService, profileService: ProfileService, debuggingService: DebuggingService, platform: Platform, statusBar: StatusBar, translate: TranslateService, events: Events, zone: NgZone, formAndFrameworkUtilService: FormAndFrameworkUtilService, appGlobalService: AppGlobalService, commonUtilService: CommonUtilService, telemetryGeneratorService: TelemetryGeneratorService, tncUpdateHandlerService: TncUpdateHandlerService, utilityService: UtilityService, headerService: AppHeaderService, logoutHandlerService: LogoutHandlerService, network: Network, appRatingService: AppRatingService, activePageService: ActivePageService, notificationSrc: LocalNotification, router: Router, location: Location, menuCtrl: MenuController, networkAvailability: NetworkAvailabilityToastService, splashScreenService: SplashScreenService, localCourseService: LocalCourseService, splaschreenDeeplinkActionHandlerDelegate: SplaschreenDeeplinkActionHandlerDelegate, utils: ApiUtilsService, networkServ: NetworkService, localStorage: LocalStorageService, db: DbService, loginHandlerService: LoginHandlerService, segmentationTagService: SegmentationTagService, mlloader: LoaderService, screenOrientation: ScreenOrientation, onboardingConfigurationService: OnboardingConfigurationService)
Parameters :
Name Type Optional
telemetryService TelemetryService No
preferences SharedPreferences No
eventsBusService EventsBusService No
notificationServices NotificationService No
systemSettingsService SystemSettingsService No
codePushExperimentService CodePushExperimentService No
deviceRegisterService DeviceRegisterService No
profileService ProfileService No
debuggingService DebuggingService No
platform Platform No
statusBar StatusBar No
translate TranslateService No
events Events No
zone NgZone No
formAndFrameworkUtilService FormAndFrameworkUtilService No
appGlobalService AppGlobalService No
commonUtilService CommonUtilService No
telemetryGeneratorService TelemetryGeneratorService No
tncUpdateHandlerService TncUpdateHandlerService No
utilityService UtilityService No
headerService AppHeaderService No
logoutHandlerService LogoutHandlerService No
network Network No
appRatingService AppRatingService No
activePageService ActivePageService No
notificationSrc LocalNotification No
router Router No
location Location No
menuCtrl MenuController No
networkAvailability NetworkAvailabilityToastService No
splashScreenService SplashScreenService No
localCourseService LocalCourseService No
splaschreenDeeplinkActionHandlerDelegate SplaschreenDeeplinkActionHandlerDelegate No
utils ApiUtilsService No
networkServ NetworkService No
localStorage LocalStorageService No
db DbService No
loginHandlerService LoginHandlerService No
segmentationTagService SegmentationTagService No
mlloader LoaderService No
screenOrientation ScreenOrientation No
onboardingConfigurationService OnboardingConfigurationService No

Methods

addNetworkTelemetry
addNetworkTelemetry(subtype: string, pageId: string)
Parameters :
Name Type Optional
subtype string No
pageId string No
Returns : void
Async applyJoyfulTheme
applyJoyfulTheme()
Returns : any
Private autoSyncTelemetry
autoSyncTelemetry()
Returns : void
checkAndroidWebViewVersion
checkAndroidWebViewVersion()
Returns : void
Private Async checkAppUpdateAvailable
checkAppUpdateAvailable()
Returns : unknown
Private Async checkCurrentOrientation
checkCurrentOrientation()
Returns : any
Private Async checkDeviceLocation
checkDeviceLocation()
Returns : any
Private checkForCodeUpdates
checkForCodeUpdates()
Returns : void
Private checkForExperiment
checkForExperiment()
Returns : void
Private Async checkForTheme
checkForTheme()
Returns : any
Private Async checkForTncUpdate
checkForTncUpdate()
Returns : any
Private Async checkGuestUserType
checkGuestUserType()
Returns : any
closePlannedMaintenanceBanner
closePlannedMaintenanceBanner()
Returns : void
closeUnPlannedMaintenanceBanner
closeUnPlannedMaintenanceBanner()
Returns : void
Private downloadProgress
downloadProgress(downloadProgress)
Parameters :
Name Optional
downloadProgress No
Returns : void
Private Async fcmTokenWatcher
fcmTokenWatcher()
Returns : any
Private Async generateImpressionEvent
generateImpressionEvent(pageId: string)
Parameters :
Name Type Optional
pageId string No
Returns : any
Private generateInteractEvent
generateInteractEvent(pageId: string)
Parameters :
Name Type Optional
pageId string No
Returns : void
Private generateNetworkTelemetry
generateNetworkTelemetry()
Returns : void
Private getCampaignParameter
getCampaignParameter()
Returns : void
Private Async getDeviceProfile
getDeviceProfile()
Returns : any
Private Async getSelectedLanguage
getSelectedLanguage()
Returns : any
Private getSystemConfig
getSystemConfig()
Returns : void
Private handleAuthAutoMigrateEvents
handleAuthAutoMigrateEvents()
Returns : void
Private handleAuthErrors
handleAuthErrors()
Returns : void
Private handleBackButton
handleBackButton()
Returns : void
handleHeaderEvents
handleHeaderEvents($event)
Parameters :
Name Optional
$event No
Returns : void
initializeApp
initializeApp()
Returns : void
iosDeeplink
iosDeeplink()
Returns : void
Private Async makeEntryInSupportFolder
makeEntryInSupportFolder()
Returns : unknown
Async menuItemAction
menuItemAction(menuName)
Parameters :
Name Optional
menuName No
Returns : any
navigateToDownloads
navigateToDownloads()
Returns : void
ngAfterViewInit
ngAfterViewInit()
Returns : void
ngOnInit
ngOnInit()
Returns : void
onConfirmationClicked
onConfirmationClicked(event)
Parameters :
Name Optional
event No
Returns : void
Private onTraceIdUpdate
onTraceIdUpdate()
Returns : void
openPlaystore
openPlaystore()
Returns : void
qrWalkthroughBackdropClicked
qrWalkthroughBackdropClicked()
Returns : void
Private Async receiveNotification
receiveNotification()
Returns : any
reloadGuestEvents
reloadGuestEvents()
Returns : void
reloadSigninEvents
reloadSigninEvents()

Enter all methods which should trigger during OnInit and User Sign-In.

Returns : void
Private Async saveDefaultSyncSetting
saveDefaultSyncSetting()
Returns : unknown
Private Async startOpenrapDiscovery
startOpenrapDiscovery()
Returns : Promise<undefined>
Private storeFCMToken
storeFCMToken(token: string)
Parameters :
Name Type Optional
token string No
Returns : void
Private subscribeEvents
subscribeEvents()
Returns : void
Private syncStatus
syncStatus(status)
Parameters :
Name Optional
status No
Returns : void
Private triggerSignInEvent
triggerSignInEvent()

Initializing the event for reloading the Tabs on Signing-In.

Returns : void

Properties

appName
Type : string
appVersion
Type : string
Public counter
Type : number
Default value : 0
eventSubscription
Type : Subscription
headerConfig
Type : object
Default value : { showHeader: true, showBurgerMenu: true, actionButtons: ['search'], }
isForeground
Type : boolean
isOnBoardingCompleted
Type : boolean
isPlannedMaintenanceStarted
Default value : false
isTimeAvailable
Default value : false
isUnplannedMaintenanceStarted
Default value : false
profile
Type : any
Default value : {}
rootPage
Type : any
rootPageDisplayed
Default value : false
routerOutlet
Type : IonRouterOutlet
Decorators :
@ViewChild('mainContent', {read: IonRouterOutlet, static: false})
selectedLanguage
Type : string
Public showWalkthroughBackDrop
Default value : false
Public sideMenuEvent
Default value : new EventEmitter<void>()
Public swipeGesture
Default value : this.platform.is('ios')? false : true
Private telemetryAutoSync
Type : TelemetryAutoSyncService
timeLeft
Type : string
toggleRouterOutlet
Default value : true
import { Location } from '@angular/common';
import {
  AfterViewInit, Component,
  EventEmitter, Inject, NgZone,
  OnInit, ViewChild
} from '@angular/core';
import { Event, NavigationExtras, NavigationStart, Router } from '@angular/router';
import { ActivePageService } from '@app/services/active-page/active-page-service';
import { LogoutHandlerService } from '@app/services/handlers/logout-handler.service';
import { TncUpdateHandlerService } from '@app/services/handlers/tnc-update-handler.service';
import { NetworkAvailabilityToastService } from '@app/services/network-availability-toast/network-availability-toast.service';
import { NotificationService as LocalNotification } from '@app/services/notification.service';
import { SplaschreenDeeplinkActionHandlerDelegate } from '@app/services/sunbird-splashscreen/splaschreen-deeplink-action-handler-delegate';
import {
  CorReleationDataType, Environment,
  ID, ImpressionType, InteractSubtype, InteractType,
  PageId
} from '@app/services/telemetry-constants';
import { Network } from '@ionic-native/network/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { IonRouterOutlet, MenuController, Platform } from '@ionic/angular';
import { Events } from '@app/util/events';
import { TranslateService } from '@ngx-translate/core';
import { CsClientStorage } from '@project-sunbird/client-services/core';
import { combineLatest, Observable, Subscription } from 'rxjs';
import { filter, mapTo, mergeMap, take, tap } from 'rxjs/operators';
import {
  AuthEventType, CodePushExperimentService, CorrelationData,
  DeviceRegisterService, ErrorEventType, EventNamespace, EventsBusService,
  GetSystemSettingsRequest, NotificationService,
  Profile, ProfileService, ProfileType, SharedPreferences,
  SunbirdSdk, DebuggingService,
  SystemSettings, SystemSettingsService, TelemetryAutoSyncService, TelemetryService
} from 'sunbird-sdk';
import {
  AppGlobalService,
  AppHeaderService, AppRatingService, CommonUtilService,
  FormAndFrameworkUtilService,
  LocalCourseService,
  LoginHandlerService, OnboardingConfigurationService, SplashScreenService, TelemetryGeneratorService,
  UtilityService
} from '../services';
import {
  AppThemes, EventTopics, GenericAppConfig,
  PreferenceKey, ProfileConstants, RouterLinks, SystemSettingsIds, AppOrientation, OnboardingScreenType
} from './app.constant';
import { EventParams } from './components/sign-in-card/event-params.interface';
import { ApiUtilsService, DbService, LoaderService, LocalStorageService, NetworkService } from './manage-learn/core';
import { SBTagModule } from 'sb-tag-manager';
import { SegmentationTagService, TagPrefixConstants } from '@app/services/segmentation-tag/segmentation-tag.service';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

declare const cordova;
declare const window;

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit, AfterViewInit {
  rootPage: any;
  public counter = 0;
  headerConfig = {
    showHeader: true,
    showBurgerMenu: true,
    actionButtons: ['search'],
  };
  public sideMenuEvent = new EventEmitter<void>();
  public showWalkthroughBackDrop = false;

  private telemetryAutoSync: TelemetryAutoSyncService;
  toggleRouterOutlet = true;
  rootPageDisplayed = false;
  profile: any = {};
  selectedLanguage: string;
  appName: string;
  appVersion: string;
  @ViewChild('mainContent', { read: IonRouterOutlet, static: false }) routerOutlet: IonRouterOutlet;
  isForeground: boolean;
  isPlannedMaintenanceStarted = false;
  isUnplannedMaintenanceStarted = false;
  timeLeft: string;
  eventSubscription: Subscription;
  isTimeAvailable = false;
  isOnBoardingCompleted: boolean;
  public swipeGesture = this.platform.is('ios')? false : true;

  constructor(
    @Inject('TELEMETRY_SERVICE') private telemetryService: TelemetryService,
    @Inject('SHARED_PREFERENCES') private preferences: SharedPreferences,
    @Inject('EVENTS_BUS_SERVICE') private eventsBusService: EventsBusService,
    @Inject('NOTIFICATION_SERVICE') private notificationServices: NotificationService,
    @Inject('SYSTEM_SETTINGS_SERVICE') private systemSettingsService: SystemSettingsService,
    @Inject('CODEPUSH_EXPERIMENT_SERVICE') private codePushExperimentService: CodePushExperimentService,
    @Inject('DEVICE_REGISTER_SERVICE') private deviceRegisterService: DeviceRegisterService,
    @Inject('PROFILE_SERVICE') private profileService: ProfileService,
    @Inject('DEBUGGING_SERVICE') private debuggingService: DebuggingService,
    private platform: Platform,
    private statusBar: StatusBar,
    private translate: TranslateService,
    private events: Events,
    private zone: NgZone,
    private formAndFrameworkUtilService: FormAndFrameworkUtilService,
    private appGlobalService: AppGlobalService,
    private commonUtilService: CommonUtilService,
    private telemetryGeneratorService: TelemetryGeneratorService,
    private tncUpdateHandlerService: TncUpdateHandlerService,
    private utilityService: UtilityService,
    private headerService: AppHeaderService,
    private logoutHandlerService: LogoutHandlerService,
    private network: Network,
    private appRatingService: AppRatingService,
    private activePageService: ActivePageService,
    private notificationSrc: LocalNotification,
    private router: Router,
    private location: Location,
    private menuCtrl: MenuController,
    private networkAvailability: NetworkAvailabilityToastService,
    private splashScreenService: SplashScreenService,
    private localCourseService: LocalCourseService,
    private splaschreenDeeplinkActionHandlerDelegate: SplaschreenDeeplinkActionHandlerDelegate,
    private utils: ApiUtilsService,
    private networkServ: NetworkService,
    private localStorage: LocalStorageService,
    private db: DbService,
    private loginHandlerService: LoginHandlerService,
    private segmentationTagService: SegmentationTagService,
    private mlloader: LoaderService,
    private screenOrientation: ScreenOrientation,
    private onboardingConfigurationService: OnboardingConfigurationService
  ) {
    this.telemetryAutoSync = this.telemetryService.autoSync;
  }

  iosDeeplink() {
      window.IonicDeeplink.route({
        '/sample': ''
        // This is not required untill NavigationController implementation
        // for all deeplinked pages
      }, (match) => {
        // TODO handle matching URLs
      }, (nomatch) => {
        // nomatch.$link - the full link data
        // Only URL has to sent to the deeplink service
        this.splaschreenDeeplinkActionHandlerDelegate.onAction({ url: nomatch.$link.url });
      });
  }

  ngOnInit() {
    this.platform.ready().then(async () => {
      if (this.platform.is('iphone') || this.platform.is('ipad')) {
        this.iosDeeplink();
      }
      this.isForeground = true;
      window['segmentation'] = SBTagModule.instance;
      if (!window['segmentation'].isInitialised) {
        window['segmentation'].init();
      }
      window['segmentation'].SBTagService.pushTag(['android'], TagPrefixConstants.ALL, true);
      this.formAndFrameworkUtilService.init();
      this.networkAvailability.init();
      this.fcmTokenWatcher(); // Notification related
      this.getSystemConfig();
      this.utilityService.getBuildConfigValue(GenericAppConfig.VERSION_NAME)
        .then(versionName => {
          this.appVersion = versionName;
          window['segmentation'].SBTagService.pushTag([this.appVersion], TagPrefixConstants.APP_VER, true);
        });
      this.checkForExperiment();
      this.receiveNotification();
      this.utilityService.getDeviceSpec()
        .then((deviceSpec) => {
          this.debuggingService.deviceId = deviceSpec.id;
          let devSpec = {
            id: deviceSpec.id,
            os: deviceSpec.os,
            make: deviceSpec.make
          };
          window['segmentation'].SBTagService.pushTag(devSpec, TagPrefixConstants.DEVICE_CONFIG, true);
          this.telemetryGeneratorService.genererateAppStartTelemetry(deviceSpec);
        });
      this.generateNetworkTelemetry();
      this.autoSyncTelemetry();
      this.subscribeEvents();
      //this.startOpenrapDiscovery();
      this.saveDefaultSyncSetting();
      this.checkAppUpdateAvailable();
      this.makeEntryInSupportFolder();
      await this.commonUtilService.populateGlobalCData();
      await this.getSelectedLanguage();
      await this.getDeviceProfile();
      if (this.appGlobalService.getUserId()) {
        this.reloadSigninEvents();
      } else {
        this.reloadGuestEvents();
      }
      this.handleAuthAutoMigrateEvents();
      this.handleAuthErrors();
      this.preferences.putString(PreferenceKey.CONTENT_CONTEXT, '').subscribe();
      window['thisRef'] = this;
      this.statusBar.styleBlackTranslucent();
      if (this.platform.is('ios')) {
        this.statusBar.styleDefault();
        if (window['Keyboard']) {
          window['Keyboard'].hideFormAccessoryBar(false);
        }
      }
      this.handleBackButton();
      this.appRatingService.checkInitialDate();
      this.getCampaignParameter();
      this.checkForCodeUpdates();
      this.checkAndroidWebViewVersion();
      await this.checkForTheme();
      this.onTraceIdUpdate();
      this.utils.initilizeML();
      this.networkServ.netWorkCheck();
      await this.applyJoyfulTheme();
    });

    this.headerService.headerConfigEmitted$.subscribe(config => {
      this.headerConfig = config;
    });

    this.commonUtilService.networkAvailability$.subscribe((available: boolean) => {
      const pageId: string = this.activePageService.computePageId(this.router.url);
      if (available) {
        this.addNetworkTelemetry(InteractSubtype.INTERNET_CONNECTED, pageId);
      } else {
        this.addNetworkTelemetry(InteractSubtype.INTERNET_DISCONNECTED, pageId);
      }
    });
    cordova.plugins.notification.local.on('click', (notification) => {
      // My data is now available in objects.heading, objects.subheading and so on.
      this.segmentationTagService.localNotificationId = notification.id;
      this.segmentationTagService.handleLocalNotificationTap();
    });

    if (cordova.plugins.notification && cordova.plugins.notification.local &&
      cordova.plugins.notification.local.launchDetails && cordova.plugins.notification.local.launchDetails.action === 'click') {
      const corRelationList: Array<CorrelationData> = [];
      this.segmentationTagService.localNotificationId = cordova.plugins.notification.local.launchDetails.id;

      corRelationList.push({
        id: this.segmentationTagService.localNotificationId ? this.segmentationTagService.localNotificationId + ''
        : '', type: CorReleationDataType.NOTIFICATION_ID
      });
      this.telemetryGeneratorService.generateNotificationClickedTelemetry(
        InteractType.LOCAL,
        this.activePageService.computePageId(this.router.url),
        undefined,
        corRelationList
      );
    }
    this.notificationSrc.setupLocalNotification();

    this.triggerSignInEvent();
    this.segmentationTagService.getPersistedSegmentaion();
    this.checkCurrentOrientation();
  }

  checkAndroidWebViewVersion() {
    let that = this;
    plugins['webViewChecker'].getCurrentWebViewPackageInfo()
      .then(function (packageInfo) {
        that.formAndFrameworkUtilService.getWebviewConfig().then(function (webviewVersion) {
          if (parseInt(packageInfo.versionName.split('.')[0], 10) <= webviewVersion) {
            document.getElementById('update-webview-container').style.display = 'block';
            that.telemetryGeneratorService.generateImpressionTelemetry(
              ImpressionType.VIEW, '',
              PageId.UPDATE_WEBVIEW_POPUP,
              Environment.HOME);
          }
        }).catch(function (err) {
          if (parseInt(packageInfo.versionName.split('.')[0], 10) <= 54) {
            document.getElementById('update-webview-container').style.display = 'block';
          }
        });
      })
      .catch(function (error) { 
        console.error(error);
      });
  }

  openPlaystore() {
    plugins['webViewChecker'].openGooglePlayPage()
      .then(function () { })
      .catch(function (error) { 
        console.error(error);
      });

    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.TOUCH,
      InteractSubtype.UPDATE_WEBVIEW_CLICKED,
      Environment.HOME,
      PageId.UPDATE_WEBVIEW_POPUP);
  }

  private getSystemConfig() {
    const getSystemSettingsRequest: GetSystemSettingsRequest = {
      id: SystemSettingsIds.HOT_CODE_PUSH_KEY
    };
    this.systemSettingsService.getSystemSettings(getSystemSettingsRequest).toPromise()
      .then((res: SystemSettings) => {
        if (res && res.value) {
          const value = JSON.parse(res.value);
          if (value.deploymentKey) {
            this.preferences.putString(PreferenceKey.DEPLOYMENT_KEY, value.deploymentKey).subscribe();
          }
        }
      }).catch(err => {
        console.log('error :', err);
      });
  }

  private checkForCodeUpdates() {
    this.preferences.getString(PreferenceKey.DEPLOYMENT_KEY).toPromise().then(deploymentKey => {
      if (codePush != null && deploymentKey) {
        const value = new Map();
        value['deploymentKey'] = deploymentKey;
        this.telemetryGeneratorService.generateInteractTelemetry(InteractType.OTHER, InteractSubtype.HOTCODE_PUSH_INITIATED,
          Environment.HOME, PageId.HOME, null, value);
        codePush.sync((status => {
          this.syncStatus(status);
        }), {
          deploymentKey
        }, (progress) => this.downloadProgress(progress));
      } else {
        this.telemetryGeneratorService.generateInteractTelemetry(InteractType.OTHER, InteractSubtype.HOTCODE_PUSH_KEY_NOT_DEFINED,
          Environment.HOME, PageId.HOME);
      }
    });
  }

  private syncStatus(status) {
    let value = new Map();
    switch (status) {
      case SyncStatus.DOWNLOADING_PACKAGE:
        value['codepushUpdate'] = 'downloading-package';
        break;
      case SyncStatus.INSTALLING_UPDATE:
        value['codepushUpdate'] = 'installing-update';
        break;
      case SyncStatus.ERROR:
        value['codepushUpdate'] = 'error-in-update';
    }
    this.telemetryGeneratorService.generateInteractTelemetry(InteractType.OTHER, InteractSubtype.HOTCODE_PUSH_INITIATED,
      Environment.HOME, PageId.HOME, null, value);
  }

  private downloadProgress(downloadProgress) {
    if (downloadProgress) {
      console.log('Downloading ' + downloadProgress.receivedBytes + ' of ' +
        downloadProgress.totalBytes);
    }
  }

  private checkForExperiment() {
    if (codePush === null) {
      return;
    }

    codePush.getCurrentPackage((update) => {
      if (update) {
        this.codePushExperimentService.getDefaultDeploymentKey().subscribe(key => {
          if (key !== update.deploymentKey && this.appVersion === update.appVersion) {
            this.codePushExperimentService.setExperimentKey(update.deploymentKey).subscribe();
            this.codePushExperimentService.setExperimentAppVersion(update.appVersion).subscribe();
          } else if (key === update.deploymentKey || this.appVersion !== update.appVersion) {
            this.codePushExperimentService.setExperimentKey('').subscribe();
            this.codePushExperimentService.setExperimentAppVersion('').subscribe();
          }
        });
      } else {
        this.codePushExperimentService.setExperimentKey('').subscribe();
        this.codePushExperimentService.setExperimentAppVersion('').subscribe();
      }
    });
  }

  /* Generates new FCM Token if not available
   * if available then on token refresh updates FCM token
   */
  private async fcmTokenWatcher() {
    const fcmToken = await this.preferences.getString(PreferenceKey.FCM_TOKEN).toPromise();
    if (!fcmToken) {
      FCMPlugin.getToken((token) => {
        this.storeFCMToken(token);
        SunbirdSdk.instance.updateDeviceRegisterConfig({ fcmToken: token });
      });
    } else {
      FCMPlugin.onTokenRefresh((token) => {
        this.storeFCMToken(token);
        SunbirdSdk.instance.updateDeviceRegisterConfig({ fcmToken: token });
      });
    }
  }

  private storeFCMToken(token: string) {
    this.preferences.putString(PreferenceKey.FCM_TOKEN, token).toPromise();
  }

  /* Notification data will be received in data variable
   * can take action on data variable
   */
  private async receiveNotification() {
    const val = await this.preferences.getString(PreferenceKey.NOTIFICAITON_RECEIVED_AT).toPromise();
    if (val) {
      const corRelationList: Array<CorrelationData> = [];
      corRelationList.push({ id: val, type: CorReleationDataType.NOTIFICATION_RECEIVED_AT });
      this.telemetryGeneratorService.generateInteractTelemetry(
        InteractType.FCM,
        '',
        Environment.HOME,
        this.activePageService.computePageId(this.router.url),
        undefined,
        undefined,
        undefined,
        corRelationList,
        ID.NOTIFICATION_RECEIVED
      );
      await this.preferences.putString(PreferenceKey.NOTIFICAITON_RECEIVED_AT, '').toPromise();
    }
    FCMPlugin.onNotification((data) => {
      data['isRead'] = data.wasTapped ? 1 : 0;
      data['actionData'] = JSON.parse(data['actionData']);
      this.notificationServices.addNotification(data).subscribe((status) => {
        this.events.publish('notification:received');
        this.events.publish('notification-status:update', { isUnreadNotifications: true });
      });
      if (data.wasTapped) {
        // Notification was received on device tray and tapped by the user.
        const value = {
          notification_id: data.id
        };
        const corRelationList: Array<CorrelationData> = [];
        const fcmId = data.id;
        corRelationList.push({ id: fcmId ? fcmId + '' : '', type: CorReleationDataType.NOTIFICATION_ID });
        this.telemetryGeneratorService.generateNotificationClickedTelemetry(
          InteractType.FCM,
          this.activePageService.computePageId(this.router.url),
          value,
          corRelationList
        );
        this.notificationSrc.notificationId = data.id || '';
        this.notificationSrc.setNotificationParams(data);
        if (this.isForeground) {
          this.notificationSrc.handleNotification();
        }
      } else {
        // Notification was received in foreground. Maybe the user needs to be notified.
      }

    },
      (success) => {
        console.log('Notification Sucess Callback', success);
      },
      (err) => {
        console.error('Notification Error Callback', err);
      });
  }

  /**
   * Initializing the event for reloading the Tabs on Signing-In.
   */
  private triggerSignInEvent() {
    this.events.subscribe(EventTopics.SIGN_IN_RELOAD, async (skipNavigation) => {
      const batchDetails = await this.preferences.getString(PreferenceKey.BATCH_DETAIL_KEY).toPromise();
      const limitedSharingContentDetails = this.appGlobalService.limitedShareQuizContent;

      if (!batchDetails && !limitedSharingContentDetails) {
        if (this.routerOutlet) {
          this.routerOutlet.deactivate();
        }
        this.toggleRouterOutlet = false;
      }

      // This setTimeout is very important for reloading the Tabs page on SignIn.
      setTimeout(async () => {
        /* Medatory for login flow
         * eventParams are essential parameters for avoiding duplicate calls to API
         * skipSession & skipProfile should be true here
         * until further change
         */
        const eventParams: EventParams = {
          skipSession: true,
          skipProfile: true
        };
        this.events.publish(AppGlobalService.USER_INFO_UPDATED, eventParams);
        this.toggleRouterOutlet = true;
        this.reloadSigninEvents();
        this.db.createDb();
        this.events.publish('UPDATE_TABS', skipNavigation);
        if (batchDetails) {
          await this.localCourseService.checkCourseRedirect();
        } else if (!skipNavigation || !skipNavigation.skipRootNavigation) {
          this.router.navigate([RouterLinks.TABS]);
        }
        this.segmentationTagService.getPersistedSegmentaion();
      }, 100);
    });
  }

  /**
   * Enter all methods which should trigger during OnInit and User Sign-In.
   */
  reloadSigninEvents() {
    this.checkForTncUpdate();
  }

  reloadGuestEvents() {
    this.checkDeviceLocation();
    this.checkGuestUserType();
  }

  private async checkGuestUserType() {
    const isAdminUser = (await this.preferences.getString(PreferenceKey.SELECTED_USER_TYPE).toPromise() === ProfileType.ADMIN);
    if (isAdminUser && this.appGlobalService.isGuestUser) {
      this.loginHandlerService.signIn();
    }
  }

  addNetworkTelemetry(subtype: string, pageId: string) {
    this.telemetryGeneratorService.generateInteractTelemetry(InteractType.OTHER,
      subtype,
      Environment.HOME,
      pageId
    );
  }

  ngAfterViewInit(): void {
    this.platform.resume.subscribe(() => {
      if (!this.appGlobalService.isNativePopupVisible) {
        this.telemetryGeneratorService.generateInterruptTelemetry('resume', '');
      }
      this.splashScreenService.handleSunbirdSplashScreenActions();
      this.checkForCodeUpdates();
      this.notificationSrc.handleNotification();
      this.isForeground = true;
      this.segmentationTagService.getPersistedSegmentaion();
    });

    this.platform.pause.subscribe(() => {
      if (!this.appGlobalService.isNativePopupVisible) {
        this.telemetryGeneratorService.generateInterruptTelemetry('background', '');
      }
      this.isForeground = false;
      this.segmentationTagService.persistSegmentation();
    });
  }

  private handleBackButton() {
    this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationStart) {
        this.rootPageDisplayed = event.url.indexOf('tabs') !== -1;
        if (this.platform.is('ios')) {
          this.swipeGesture = !this.rootPageDisplayed;
        }
      }
    });
    this.platform.backButton.subscribeWithPriority(0, async () => {
      if (this.router.url === RouterLinks.LIBRARY_TAB || this.router.url === RouterLinks.COURSE_TAB
        || this.router.url === RouterLinks.HOME_TAB || (this.router.url === RouterLinks.SEARCH && !this.appGlobalService.isDiscoverBackEnabled)
        || this.router.url === RouterLinks.DOWNLOAD_TAB || this.router.url === RouterLinks.PROFILE_TAB ||
        this.router.url === RouterLinks.GUEST_PROFILE_TAB || this.router.url === RouterLinks.ONBOARDING_DISTRICT_MAPPING
        || this.router.url.startsWith(RouterLinks.HOME_TAB)
        || (this.router.url === `/${RouterLinks.USER_TYPE_SELECTION}` && this.onboardingConfigurationService.initialOnboardingScreenName === OnboardingScreenType.USER_TYPE_SELECTION)
        || (this.router.url === `/${RouterLinks.PROFILE_SETTINGS}` && this.onboardingConfigurationService.initialOnboardingScreenName === OnboardingScreenType.PROFILE_SETTINGS)
        ) {
        if (await this.menuCtrl.isOpen()) {
          this.menuCtrl.close();
        } else {
          if (this.platform.is('ios')) {
            this.headerService.showHeaderWithHomeButton();
          } else {
            this.commonUtilService.showExitPopUp(this.activePageService.computePageId(this.router.url), Environment.HOME, false);
          }
        }
      } else if ((this.router.url === RouterLinks.SEARCH) && this.appGlobalService.isDiscoverBackEnabled) {
        this.headerService.sidebarEvent('back');
      } else {
        if (this.location.back && !this.rootPageDisplayed) {
          this.mlloader.stopLoader()
          this.location.back();
        }
      }
    });
  }

  private generateNetworkTelemetry() {
    const value = new Map();
    value['network-type'] = this.network.type;
    this.telemetryGeneratorService.generateInteractTelemetry(InteractType.OTHER,
      InteractSubtype.NETWORK_STATUS, Environment.HOME, PageId.SPLASH_SCREEN, undefined, value);
  }

  private subscribeEvents() {
    this.events.subscribe(EventTopics.TAB_CHANGE, (pageId) => {
      this.zone.run(() => {
        this.generateInteractEvent(pageId);
        // Added below code to generate Impression Before Interact for Library,Courses,Profile
        this.generateImpressionEvent(pageId);
      });
    });

    this.translate.onLangChange.subscribe((params) => {
      if (params.lang === 'ur') {
        document.documentElement.dir = 'rtl';
      } else {
        document.documentElement.dir = 'ltr';
      }
    });
    // planned maintenance
    this.eventSubscription = this.eventsBusService.events(EventNamespace.ERROR).pipe(
      filter((event) => event.type === ErrorEventType.PLANNED_MAINTENANCE_PERIOD),
      take(1)
    ).subscribe(() => {
      this.isPlannedMaintenanceStarted = true;
      this.isOnBoardingCompleted = this.appGlobalService.isOnBoardingCompleted;
      if (this.isPlannedMaintenanceStarted) {
        this.telemetryGeneratorService.generateImpressionTelemetry(
          ImpressionType.VIEW,
          '',
          PageId.PLANNED_MAINTENANCE_BANNER,
          this.isOnBoardingCompleted ? Environment.HOME : Environment.ONBOARDING
        );
        let intervalRef;
        const backButtonSubscription = this.platform.backButton.subscribeWithPriority(13, () => {
          backButtonSubscription.unsubscribe();
          this.isPlannedMaintenanceStarted = false;
          if (intervalRef) {
            clearInterval(intervalRef);
            intervalRef = undefined;
          }
        });
        // for timer optional
        // const second = 1000,
        //     minute = second * 60,
        //     hour = minute * 60,
        //     day = hour * 24;
        //
        // const countDown = new Date('Aug 14, 2020 00:00:00').getTime();
        // intervalRef = setInterval(() => {
        //   this.isTimeAvailable = true;
        //   const now = new Date().getTime(),
        //           distance = countDown - now;
        //
        //       document.getElementById('timer').innerText = `${Math.floor((distance % (day)) / (hour))} : ${Math.floor((distance % (hour)) / (minute))} : ${Math.floor((distance % (minute)) / second)}`;
        //
        //     }, second);
      }
    });
    // unplanned maintenance
    // this.events.subscribe('EventTopics:maintenance:unplanned', (data) => {
    //   this.isUnplannedMaintenanceStarted = data.isUnplannedMaintenanceStarted;
    //   if (this.isUnplannedMaintenanceStarted) {
    //     this.timeLeft = '3';
    //     window.document.body.classList.add('show-maintenance');
    //   }
    // });
    this.debuggingService.enableDebugging().subscribe((isDebugMode) => {
        this.events.publish('debug_mode', isDebugMode);
    });
  }

  closeUnPlannedMaintenanceBanner() {
    window.document.body.classList.remove('show-maintenance');
    this.isUnplannedMaintenanceStarted = false;
  }

  private generateInteractEvent(pageId: string) {
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.TOUCH,
      InteractSubtype.TAB_CLICKED,
      Environment.HOME,
      pageId ? pageId.toLowerCase() : PageId.QRCodeScanner);
  }

  private async generateImpressionEvent(pageId: string) {
    pageId = pageId.toLowerCase();
    const env = pageId.localeCompare(PageId.PROFILE) ? Environment.HOME : Environment.USER;
    const corRelationList: Array<CorrelationData> = [];
    if (pageId === PageId.LIBRARY) {
      const currentProfile: Profile = this.appGlobalService.getCurrentUser();
      corRelationList.push({ id: currentProfile.board ? currentProfile.board.join(',') : '', type: CorReleationDataType.BOARD });
      corRelationList.push({ id: currentProfile.medium ? currentProfile.medium.join(',') : '', type: CorReleationDataType.MEDIUM });
      corRelationList.push({ id: currentProfile.grade ? currentProfile.grade.join(',') : '', type: CorReleationDataType.CLASS });
      corRelationList.push({ id: currentProfile.profileType, type: CorReleationDataType.USERTYPE });
    } else if (pageId === PageId.COURSES) {
      const channelId = await this.preferences.getString(PreferenceKey.PAGE_ASSEMBLE_ORGANISATION_ID).toPromise();
      if (channelId) {
        corRelationList.push({ id: channelId, type: CorReleationDataType.SOURCE });
      }
    }

    this.telemetryGeneratorService.generateImpressionTelemetry(
      ImpressionType.VIEW, '',
      pageId ? pageId : PageId.HOME,
      env, undefined, undefined, undefined, undefined,
      corRelationList);
  }

  private async checkForTncUpdate() {
    this.appGlobalService.isSignInOnboardingCompleted = false;
    await this.tncUpdateHandlerService.checkForTncUpdate();
  }

  private async checkDeviceLocation() {
    if (!(await this.commonUtilService.isDeviceLocationAvailable())) {
      const profile = await this.profileService.getActiveSessionProfile({ requiredFields: ProfileConstants.REQUIRED_FIELDS }).toPromise();
      if (await this.appGlobalService.getProfileSettingsStatus(profile)) {
        const navigationExtras: NavigationExtras = {
          state: {
            isShowBackButton: false
          }
        };
        await this.router.navigate(['/', RouterLinks.DISTRICT_MAPPING], navigationExtras);
        this.splashScreenService.handleSunbirdSplashScreenActions();
      }
    }
  }

  private async getSelectedLanguage() {
    const selectedLanguage = await this.preferences.getString(PreferenceKey.SELECTED_LANGUAGE_CODE).toPromise();
    window['segmentation'].SBTagService.pushTag([selectedLanguage], TagPrefixConstants.USER_LANG, true);
    if (selectedLanguage) {
      this.translate.use(selectedLanguage);
    }
  }

  private async makeEntryInSupportFolder() {
    return new Promise<void>((resolve => {
      (window).sbutility.makeEntryInSunbirdSupportFile((result) => {
        this.preferences.putString(PreferenceKey.KEY_SUNBIRD_SUPPORT_FILE_PATH, result).toPromise().then();
        resolve();
      }, () => {
      });
    }));
  }

  private async saveDefaultSyncSetting() {
    return this.preferences.getString(PreferenceKey.SYNC_CONFIG).toPromise()
      .then(val => {
        if (val === undefined || val === '' || val === null) {
          this.preferences.putString(PreferenceKey.SYNC_CONFIG, 'ALWAYS_ON').toPromise().then();
        }
      });
  }

  private async startOpenrapDiscovery(): Promise<undefined> {
      return new Observable((observer) => {
        (window).openrap.startDiscovery(
          (response: { ip: string, actionType: 'connected' | 'disconnected' }) => {
            observer.next(response);
          }, (e) => {
            observer.error(e);
          }
        );
      }).pipe(
        tap((response: { ip?: string, actionType: 'connected' | 'disconnected' }) => {
          const values = new Map();
          values['openrapInfo'] = response;
          this.telemetryGeneratorService.generateInteractTelemetry(InteractType.OTHER,
            response.actionType === 'connected' ? InteractSubtype.OPENRAP_DEVICE_CONNECTED : InteractSubtype.OPENRAP_DEVICE_DISCONNECTED,
            Environment.HOME,
            Environment.HOME, undefined,
            values);
          SunbirdSdk.instance.updateContentServiceConfig({
            host: response.actionType === 'connected' ? response.ip : undefined
          });

          SunbirdSdk.instance.updatePageServiceConfig({
            host: response.actionType === 'connected' ? response.ip : undefined
          });

          SunbirdSdk.instance.updateTelemetryConfig({
            host: response.actionType === 'connected' ? response.ip : undefined
          });
        }),
        mapTo(undefined)
      ).toPromise();
  }

  private async checkAppUpdateAvailable() {
    return this.formAndFrameworkUtilService.checkNewAppVersion()
      .then(result => {
        if (result) {
          setTimeout(() => {
            if(!this.platform.is('ios')) {
              this.events.publish('force_optional_upgrade', result);
            }
          }, 5000);
        }
      })
      .catch(err => {
        console.error('checkNewAppVersion err', err);
      });
  }


  private autoSyncTelemetry() {
    this.telemetryAutoSync.start(30 * 1000).pipe(
      mergeMap(() => {
        return combineLatest([
          this.platform.pause.pipe(tap(() => this.telemetryAutoSync.pause())),
          this.platform.resume.pipe(tap(() => this.telemetryAutoSync.continue()))
        ]);
      })
    ).subscribe();
  }

  initializeApp() {
    this.headerService.headerConfigEmitted$.subscribe(config => {
      this.headerConfig = config;
    });
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
    });
  }

  handleHeaderEvents($event) {
    if ($event.name === 'back') {
      const routeUrl = this.router.url;

      if ((routeUrl.indexOf(RouterLinks.USER_TYPE_SELECTION) !== -1)
        || (routeUrl.indexOf(RouterLinks.CHAPTER_DETAILS) !== -1)
        || (routeUrl.indexOf(RouterLinks.CURRICULUM_COURSES) !== -1)
        || (routeUrl.indexOf(RouterLinks.ACTIVE_DOWNLOADS) !== -1)
        || (routeUrl.indexOf(RouterLinks.COLLECTION_DETAIL_ETB) !== -1)
        || (routeUrl.indexOf(RouterLinks.COLLECTION_DETAILS) !== -1)
        || (routeUrl.indexOf(RouterLinks.CONTENT_DETAILS) !== -1)
        || (routeUrl.indexOf(RouterLinks.ENROLLED_COURSE_DETAILS) !== -1)
        || (routeUrl.indexOf(RouterLinks.FAQ_HELP) !== -1)
        || (routeUrl.indexOf(RouterLinks.PROFILE_SETTINGS) !== -1)
        || (routeUrl.indexOf(RouterLinks.QRCODERESULT) !== -1)
        || (routeUrl.indexOf(RouterLinks.STORAGE_SETTINGS) !== -1)
        || (routeUrl.indexOf(RouterLinks.EXPLORE_BOOK) !== -1)
        || (routeUrl.indexOf(RouterLinks.PERMISSION) !== -1)
        || (routeUrl.indexOf(RouterLinks.LANGUAGE_SETTING) !== -1)
        || (routeUrl.indexOf(RouterLinks.MY_GROUPS) !== -1)
        || (routeUrl.indexOf(`${RouterLinks.PROJECT}/${RouterLinks.DETAILS}`) !== -1)
        || (routeUrl.indexOf(`${RouterLinks.SETTINGS}/${RouterLinks.DATA_SYNC}`) !== -1)
        || (routeUrl.indexOf(`${RouterLinks.ADD_FILE}/`) !== -1)
      ) {
        this.headerService.sidebarEvent($event);
        return;
      } else {
        if (this.router.url === RouterLinks.LIBRARY_TAB || this.router.url === RouterLinks.COURSE_TAB
          || this.router.url === RouterLinks.HOME_TAB || (this.router.url === RouterLinks.SEARCH_TAB && !this.appGlobalService.isDiscoverBackEnabled)
          || this.router.url === RouterLinks.DOWNLOAD_TAB || this.router.url === RouterLinks.PROFILE_TAB ||
          this.router.url === RouterLinks.GUEST_PROFILE_TAB || this.router.url.startsWith(RouterLinks.HOME_TAB)) {
            if (this.platform.is('ios')) {
              this.headerService.showHeaderWithHomeButton();
            } else {
              this.commonUtilService.showExitPopUp(this.activePageService.computePageId(this.router.url), Environment.HOME, false).then();
            }
        } else if (this.router.url === RouterLinks.SEARCH_TAB && this.appGlobalService.isDiscoverBackEnabled) {
          this.headerService.sidebarEvent($event);
        } else {
          if (this.location.back) {
            this.location.back();
          }
        }
      }
    } else {
      this.headerService.sidebarEvent($event);
    }
  }

  async menuItemAction(menuName) {
    switch (menuName.menuItem) {
      case 'MY_GROUPS':
        this.telemetryGeneratorService.generateInteractTelemetry(
          InteractType.TOUCH,
          InteractSubtype.MY_GROUPS_CLICKED,
          Environment.USER,
          PageId.PROFILE
        );
        const navigationExtrasUG: NavigationExtras = { state: { profile: this.profile } };
        this.router.navigate([`/${RouterLinks.MY_GROUPS}`], navigationExtrasUG);
        break;

      case 'SETTINGS': {
        this.telemetryGeneratorService.generateInteractTelemetry(
          InteractType.TOUCH,
          InteractSubtype.SETTINGS_CLICKED,
          Environment.USER,
          PageId.PROFILE);
        this.router.navigate([`/${RouterLinks.SETTINGS}`]);
        break;
      }
      case 'LANGUAGE': {
        this.telemetryGeneratorService.generateInteractTelemetry(
          InteractType.TOUCH,
          InteractSubtype.LANGUAGE_CLICKED,
          Environment.USER,
          PageId.PROFILE);
        this.router.navigate([`/${RouterLinks.LANGUAGE_SETTING}`, true]);
        break;
      }

      case 'HELP':
        this.telemetryGeneratorService.generateInteractTelemetry(
          InteractType.TOUCH,
          InteractSubtype.HELP_CLICKED,
          Environment.USER,
          PageId.PROFILE);
        this.router.navigate([`/${RouterLinks.FAQ_HELP}`]);
        break;

      case 'LOGOUT':
        this.logoutHandlerService.onLogout();
        break;

      case 'UPDATE':
        cordova.plugins.InAppUpdateManager.checkForImmediateUpdate(
          () => { },
          () => { }
        );
        break;

      case 'IMPORT':
        this.utilityService.openFileManager().then((success) => {
          console.log('-----openFileManager-----', success);
        }).catch((err) => {
          console.log('---------error------', err);
        });
        break;
      case 'LOGIN':
        if (!this.commonUtilService.networkInfo.isNetworkAvailable) {
          this.commonUtilService.showToast('NEED_INTERNET_TO_CHANGE');
        } else {
          const routerValue = this.router.url.split('/').pop();
          if (routerValue === PageId.USER || routerValue === PageId.RESOURCES) {
            this.router.navigate([RouterLinks.SIGN_IN], {state: {source: routerValue}});
          } else {
            this.router.navigate([RouterLinks.SIGN_IN]);
          }
        }
        break;
      case 'MLREPORTS':
        this.router.navigate([RouterLinks.REPORTS], {});
        break;
      case 'ORIENTATION':
        const currentOrientation = await this.preferences.getString(PreferenceKey.ORIENTATION).toPromise();
        if (currentOrientation === AppOrientation.LANDSCAPE) {
          this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
          this.preferences.putString(PreferenceKey.ORIENTATION, AppOrientation.PORTRAIT).toPromise();
          this.events.publish(EventTopics.ORIENTATION);
        } else {
          this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
          this.preferences.putString(PreferenceKey.ORIENTATION, AppOrientation.LANDSCAPE).toPromise();
          this.events.publish(EventTopics.ORIENTATION);
        }
    }
  }

  private handleAuthAutoMigrateEvents() {
    this.eventsBusService.events(EventNamespace.AUTH).pipe(
      filter((e) => e.type === AuthEventType.AUTO_MIGRATE_SUCCESS || e.type === AuthEventType.AUTO_MIGRATE_FAIL),
    ).subscribe((e) => {
      switch (e.type) {
        case AuthEventType.AUTO_MIGRATE_SUCCESS: {
          this.commonUtilService.showToast('AUTO_MIGRATION_SUCCESS_MESSAGE');
          break;
        }
        case AuthEventType.AUTO_MIGRATE_FAIL: {
          this.commonUtilService.showToast('AUTO_MIGRATION_FAIL_MESSAGE');
          break;
        }
      }
    });
  }

  private handleAuthErrors() {
    this.eventsBusService.events(EventNamespace.ERROR).pipe(
      filter((e) => e.type === ErrorEventType.AUTH_TOKEN_REFRESH_ERROR),
    ).subscribe(() => {
      this.logoutHandlerService.onLogout();
    });
  }

  private getCampaignParameter() {
    this.preferences.getString(PreferenceKey.CAMPAIGN_PARAMETERS).toPromise().then((data) => {
      if (data) {
        const response = JSON.parse(data);
        const utmValue = response['val'];
        if (response.val && response.val.length) {
          this.splaschreenDeeplinkActionHandlerDelegate.checkUtmContent(response.val);
        }
        const utmTelemetry = {
          utm_data: utmValue
        };
        this.telemetryGeneratorService.generateInteractTelemetry(
          InteractType.OTHER,
          InteractSubtype.UTM_INFO,
          Environment.HOME,
          PageId.HOME,
          undefined,
          utmTelemetry);
        this.utilityService.clearUtmInfo();
      }
    })
      .catch(error => {
        console.log('Error is', error);
      });
  }

  qrWalkthroughBackdropClicked() {
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.TOUCH,
      InteractSubtype.WALKTHROUGH_BACKDROP_CLICKED,
      Environment.ONBOARDING,
      PageId.LIBRARY,
    );
  }

  onConfirmationClicked(event) {
    event.stopPropagation();
    this.showWalkthroughBackDrop = false;
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.TOUCH,
      InteractSubtype.WALKTHROUGH_CONFIRMATION_CLICKED,
      Environment.ONBOARDING,
      PageId.LIBRARY
    );
  }

  private async getDeviceProfile() {
    if (!(await this.commonUtilService.isDeviceLocationAvailable())
      && !(await this.commonUtilService.isIpLocationAvailable())) {
      this.deviceRegisterService.getDeviceProfile().toPromise().then(async (response) => {
        if (response.userDeclaredLocation) {
          if (this.appGlobalService.isGuestUser) {
            await this.preferences.putString(PreferenceKey.GUEST_USER_LOCATION, JSON.stringify(response.userDeclaredLocation)).toPromise();
          }
          await this.preferences.putString(PreferenceKey.DEVICE_LOCATION, JSON.stringify(response.userDeclaredLocation)).toPromise();
        } else if (response.ipLocation) {
          const ipLocationMap = new Map();
          if (response.ipLocation.state) {
            ipLocationMap['state'] = response.ipLocation.state;
            if (response.ipLocation.district) {
              ipLocationMap['district'] = response.ipLocation.district;
            }
          }
          await this.preferences.putString(PreferenceKey.IP_LOCATION, JSON.stringify(ipLocationMap)).toPromise();
        }
      });
    }
  }

  navigateToDownloads() {
    this.isPlannedMaintenanceStarted = false;
    this.router.navigate([RouterLinks.DOWNLOAD_TAB]);
  }


  closePlannedMaintenanceBanner() {
    this.isPlannedMaintenanceStarted = false;
  }

  private async checkForTheme() {
    const selectedTheme = await this.preferences.getString(PreferenceKey.CURRENT_SELECTED_THEME).toPromise();
    if (selectedTheme === AppThemes.JOYFUL) {
      await this.headerService.showStatusBar();
    } else {
      this.headerService.hideStatusBar();
    }
  }

  private onTraceIdUpdate() {
    this.preferences.addListener(CsClientStorage.TRACE_ID, (value) => {
      if (value) {
        // show toast
      }
    });
  }

  async applyJoyfulTheme() {
      await this.preferences.putString('current_selected_theme', AppThemes.JOYFUL).toPromise();
      this.headerService.showStatusBar();
  }

  private async checkCurrentOrientation() {
    const currentOrientation = await this.preferences.getString(PreferenceKey.ORIENTATION).toPromise();
    if (currentOrientation === AppOrientation.LANDSCAPE) {
      this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);
      this.preferences.putString(PreferenceKey.ORIENTATION, AppOrientation.LANDSCAPE).toPromise();
    } else {
      this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
      this.preferences.putString(PreferenceKey.ORIENTATION, AppOrientation.PORTRAIT).toPromise();
    }
  }
}

<ion-app>

  <div style="z-index: 1;" >
    <app-application-header *ngIf="!isPlannedMaintenanceStarted" [headerConfig]="headerConfig" (headerEvents)="handleHeaderEvents($event);"
                            (sideMenuItemEvent)="menuItemAction($event)"></app-application-header>

    <div class="unplanned-maintenance-banner">
      <ion-grid>
        <ion-row class="ion-justify-content-between ion-align-items-center">
          <ion-col size="1">
            <img style="width: 1.125rem; height: 1.125rem;" src="assets/imgs/ic_info_white.svg" alt="">
          </ion-col>
          <ion-col style="color: white;" size="10">
            {{'MAINTENANCE_MESSAGE' | translate:{'%timeLeft': '3'} }}
          </ion-col>
          <ion-col size="1">
            <img (click)="closeUnPlannedMaintenanceBanner()" style="width: 1.125rem; height: 1.125rem;" src="assets/imgs/ic_action_close_white.svg" alt="">
          </ion-col>
        </ion-row>
      </ion-grid>
    </div>

  </div>

  <ion-split-pane contentId="mainContent">
    <ion-router-outlet #ionRouterOutlet id="mainContent" main [swipeGesture]="false"
      [ngClass]="{'need-header-space':headerConfig?.showHeader, '':!headerConfig?.showHeader}"></ion-router-outlet>
  </ion-split-pane>

  <div id="planned-maintenance-banner" [hidden]="!isPlannedMaintenanceStarted">
    <img style="float: right; padding: 16px;" src="assets/imgs/close_tutorial.svg" alt="" (click)="closePlannedMaintenanceBanner()">
    <!--Image-->
    <img src="../assets/imgs/ic_maintenance.svg" alt="maintenance" style="margin-top: 50%;">
    <!-- some text -->
    <div id="planned-maintenance-text">
      <p *ngIf="!isTimeAvailable">{{'PLANNED_MAINTENANCE_TEXT' | translate}}</p>
      <p *ngIf="isTimeAvailable">{{'PLANNED_MAINTENANCE_TEXT_WITH_TIME' | translate}}</p>
    </div>
    <!--Timer-->
    <div id="timer"></div>
    <!-- another text -->
    <p id="maintenance-sub-text" *ngIf="isOnBoardingCompleted">{{'MAINTENANCE_SUB_TEXT' | translate}}</p>
    <div class="text-center" *ngIf="isOnBoardingCompleted">
      <ion-button id="navigate-downloads" (click)="navigateToDownloads()">{{'GO_TO_DOWNLOADS' | translate}}</ion-button>
    </div>
  </div>

  <div id="update-webview-container"
    style="position: fixed;top: 0;left: 0;right: 0;bottom: 0;z-index: 10;background-color: rgba(0, 0, 0, 0.59);opacity: 1;display: none;">
    <div id="update-webview-content"
      style="position: fixed;top: 0;left: 0;right: 0;bottom: 0;z-index: 11;width: 80%;height: 12.188rem;background-color: #eee; margin: auto;">
      <div style="height:12.188rem;position: relative;">
        <div>
          <h3
            style="text-align: center;background-color: #024f9d; color: #fff;margin: 0;padding: 8px; font-size: 18px;">
            {{'UPDATE_REQUIRED' | translate}}
          </h3>
        </div>
        <div style="padding: 15px 0; font-size: 16px; color: #333;width:80%;margin: auto;">
          <p style="margin: 0;">{{'WEBVIEW_UPDATE_TEXT' | translate}}</p>
        </div>
        <div style="position: absolute; width: 100%; bottom: 15px;text-align: center;">
          <button (click)="openPlaystore()"
            style="color: #fff;background: #024f9d;padding: 10px;width: 80%;margin: auto;">{{'DOWNLOAD_NOW' | translate}}</button>
        </div>
      </div>
    </div>
  </div>

</ion-app>
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""