import { Component, OnInit } from '@angular/core';
import { Platform, Events, MenuController, ModalController, NavController } from '@ionic/angular';
import { TranslatorService } from './hmg-common/services/translator/translator.service';
import { CommonService } from './hmg-common/services/common/common.service';
import { AuthenticationService } from './hmg-common/services/authentication/authentication.service';
import { AuthenticatedUser } from './hmg-common/services/authentication/models/authenticated-user';
import { KeyboardService } from './hmg-common/services/keyboard/keyboard.service';
import { PushService } from '../../src/app/hmg-common/services/push/push.service';
import { LazyLoadingService } from './hmg-common/services/lazy-loading/lazy-loading.service';
import { DomSanitizer } from '@angular/platform-browser';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { Router, NavigationEnd } from '@angular/router';
import { DigitalIdComponent } from './authentication/digital-id/digital-id.component';
import { checkAndUpdatePureExpressionInline } from '@angular/core/src/view/pure_expression';
import { FirebaseX } from '@ionic-native/firebase-x/ngx';
import { BusinessCardComponent } from './authentication/business-card/business-card.component';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.scss'],
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
  start: any = false;
  menuList: any = [];
  User_name_Emp = '';
  user_image: any = '../assets/imgs/profile.png';
  menuSide = 'left';
  notBadge: number;
  companyUrl = '../assets/imgs/CSLogo.png';
  companyDesc = 'Powered By Cloud Solutions';
  direction = 'ltr';
  User_Job_name: string;
  public logoutFlage: any = false;
  user: boolean;
  deviceToken: string;
  TeamFlag: string = 'false';
  isIOS = false;
  userInfo;
  public requestGetLoginInfo: {
    DeviceType: string;
    DeviceToken: string; // this.deviceToken
  };

  private digitalIDUser: any;

  constructor(
    public ts: TranslatorService,
    private cs: CommonService,
    private lazyLoadingService: LazyLoadingService,
    private platform: Platform,
    private events: Events,
    private keyboardService: KeyboardService,
    private menu: MenuController,
    private authService: AuthenticationService,
    private sanitizer: DomSanitizer,
    public pushService: PushService,
    private splashScreen: SplashScreen,
    public router: Router,
    public modalController: ModalController,
    public nav: NavController,
    public firebasex: FirebaseX
  ) {
    this.events.subscribe('img-change', displayImg => {
      console.log('app compont: ' + displayImg);
      this.user_image = this.sanitizer.bypassSecurityTrustUrl('data:Image/*;base64,' + displayImg);
    });
  }

  ngOnInit() {
    this.initializeApp();
  }

  private hideSplashScreen() {
    setTimeout(() => {
      this.splashScreen.hide();
    }, 1000);
  }

  public initializeApp() {
    this.cs.startLoading();
    this.start = false;
    this.menu.enable(false);
    this.lazyLoadingService.monitorLazyLoading(15, true);
    this.platform.ready().then(() => {
      this.hideSplashScreen();
      this.ts.loadResources(() => {
        this.isIOS = this.platform.is('ios') ? true : false;
        this.initializeDirection();
        this.monitorAnalytics();
        this.start = true;
        if (this.isIOS) {
          this.monitUrlChange();
        }
        this.watchLanguageChangeEvents();
        this.subscribeEvents();
        this.keyboardService.watchKeyboard();
        this.startReceivingPushService();
      });
    });
  }

  private monitUrlChange() {
    this.router.events.subscribe((val) => {
      if (this.router.isActive('/authentication/login', true)) {
        this.direction = 'ltr';
      } else {
        this.direction = TranslatorService.getCurrentDirection();
      }
    });
  }

  public monitorAnalytics() {
    this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
        const lastIndex = val.urlAfterRedirects.lastIndexOf('/');
        const currentPageName = val.urlAfterRedirects.substr(lastIndex + 1);
        this.setScreenNameAnalytics(currentPageName);
      }
    });
  }

  public setScreenNameAnalytics(currentPageName: string) {
    try {
      this.firebasex.setScreenName(currentPageName).then((result)=>{
        console.log(result);
      });
    } catch (Error) { }
  }

  private startReceivingPushService() {
    this.pushService.startReceiving();
    setTimeout(() => {
      console.log(' in setTimeout startReceiving');
      this.getLastLoginInfo();

    }, 4000);
  }

  public subscribeEvents() {
    this.platform.backButton.subscribe(() => {
      if (this.router.isActive('/authentication/login', true)) {
        navigator['app'].exitApp();
      } else if (this.router.isActive('/home', true)) {

        this.nav.navigateRoot('/home');
      }
    });
    this.events.subscribe('setMenu', () => {
      const user = this.authService.loadAuthenticatedUser().subscribe((user: AuthenticatedUser) => {
        if (user) {
          console.log(user);

          localStorage.setItem("digitalIDUser", JSON.stringify(user));
          this.digitalIDUser = user//JSON.stringify(user);
          this.companyUrl = user.CompanyImageURL ? user.CompanyImageURL : '../assets/imgs/CSLogo.png';
          this.companyDesc = user.CompanyImageDescription ? user.CompanyImageDescription : 'Powered By Cloud Solutions';
          this.User_name_Emp = user.EMPLOYEE_DISPLAY_NAME;


          this.authService.checkAds({
            EmployeeNumber: '',
            ItgEnableAt: "After Service Submission", //After Service Submission
            ItgServiceName: "Login"
          }, () => { }, this.ts.trPK('general', 'ok')).subscribe(res => {

            var result = JSON.parse(res.Mohemm_ITG_ResponseItem).result.data;

            this.cs.sharedService.setSharedData(
              result,
              AuthenticationService.SERVEY_DATA
            )
            if (!CommonService.SKIP && result) {
              if (result.notificationType == 'Survey') {
                this.cs.navigateForward('/erm-channel/survey');
              } else {
                this.authService.adsDetails({
                  "ItgNotificationMasterId": result['notificationMasterId']
                },
                  () => { }, this.ts.trPK('general', 'ok')
                ).subscribe((result) => {
                  var data = result.Mohemm_ITG_ResponseItem;
                  if (data) {
                    this.cs.sharedService.setSharedData(
                      JSON.parse(data),
                      AuthenticationService.ADS_DATA
                    );
                    this.cs.navigateForward('/erm-channel/home');
                  }

                })

              }

            }


          });

          if (this.cs.getUpdateImage().status) {
            this.user_image = this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,' + this.cs.getUpdateImage().img);
          } else {
            this.user_image = user.EMPLOYEE_IMAGE ? 'data:image/png;base64,' + user.EMPLOYEE_IMAGE : '../assets/imgs/profile.png';
          }
          // this.User_Job_name = user.JOB_NAME;
          let jobTitle = user.POSITION_NAME.split('.');
          if (jobTitle && jobTitle.length > 1) {
            this.User_Job_name = jobTitle[0] + " " + jobTitle[1];
          }​
          //erm channel
          // if (!CommonService.SKIP)
          //   this.cs.navigateForward('/erm-channel/survey');
        } else {
          console.log(user);
        }
      });
    });
    this.events.subscribe('getNotCount', badge => { this.notBadge = badge; });
    this.events.subscribe('myTeamFlag', myTeamFlag => { this.TeamFlag = myTeamFlag; });
  }

  private initializeDirection() {
    if (this.isIOS) {
      if (this.router.isActive('/authentication/login', true)) {
        this.direction = 'ltr';
      } else {
        this.direction = TranslatorService.getCurrentDirection();
      }
    } else {
      this.direction = TranslatorService.getCurrentDirection();
    }
  }

  private watchLanguageChangeEvents() {
    this.events.subscribe(TranslatorService.CHANGE_EVENT, () => {
      this.start = false;
      this.initializeDirection();
      setTimeout(() => {
        this.start = true;
      }, 100);
    });
  }

  public logout() {
    this.cs.sharedService.clearAll();
    this.menu.enable(false);
    this.logoutFlage = true;
    this.events.publish('logoutFlage', this.logoutFlage);
    this.cs.setUpdateImage('', false);
    this.TeamFlag = 'false';
    this.getLastLoginInfo();
  }

  public openMyTeamPage() {
    this.menu.toggle();
    this.cs.openMyTeamPage();
  }

  public openMyRequestPage() {
    this.menu.toggle();
    this.cs.openMyRequestPage();
  }

  public profile() {
    this.cs.openProfile('sideMenu');
    this.menu.toggle();
  }

  public openNotification() {
    this.cs.openNotificationPage();
    this.menu.toggle();
  }

  public openChangePassword() {
    this.cs.openChangePassword();
    this.menu.toggle();
  }

  async openDigitalId() {
    const modal = await this.modalController.create({
      component: DigitalIdComponent,
      cssClass: 'digital-id-modal-css',
      componentProps: {
        'userInfo': this.digitalIDUser//JSON.parse(this.digitalIDUser)
      }
    });
    return await modal.present();
  }
  async openBusinessCard() {
    this.userInfo = this.cs.sharedService.getSharedData('bussiness-card-info', false);
    const modal = await this.modalController.create({
      component: BusinessCardComponent,
      cssClass: 'digital-id-modal-css',
      componentProps: {
        'userInfo': this.userInfo
      }
    });
    return await modal.present();
  }

  private changeImage() {
    this.cs.openChangeImagePage();
    this.menu.toggle();
  }

  public closeMenu() {
    this.menu.toggle();
  }

  public getLastLoginInfo() {
    this.deviceToken = this.cs.getDeviceToken();
    if (this.deviceToken) {
      console.log('login enabled first time: ' + this.deviceToken);
    } else {
      this.pushService.startReceiving();
      setTimeout(() => {
        this.deviceToken = localStorage.getItem('deviceToken');
      }, 1000);
    }

    this.requestGetLoginInfo = {
      DeviceType: this.cs.getDeviceType(),
      DeviceToken: this.deviceToken
    };

    this.authService.getLoginInfo(this.requestGetLoginInfo, () => { }, this.ts.trPK('general', 'ok')).subscribe(res => {
      if (this.cs.validResponse(res)) {
        if (res.Mohemm_GetMobileLoginInfoList.length > 0) {
          this.cs.sharedService.setSharedData(res.Mohemm_GetMobileLoginInfoList[0], AuthenticationService.IMEI_USER_DATA);
          this.user = true;
          this.events.publish('user', this.user);

          if (this.logoutFlage) {
            this.cs.openLogin();
          }
        } else {
          this.user = false;
          this.events.publish('user', this.user);

          if (this.logoutFlage) {
            this.cs.openLogin();
          }
        }
      } else { }
    });
  }
}
