import { EitService } from './../eit/services/eit.service';
import { Component, OnInit } from '@angular/core';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { Platform, MenuController, Events, ActionSheetController, ModalController } from '@ionic/angular';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { AuthenticatedUser } from 'src/app/hmg-common/services/authentication/models/authenticated-user';
import { MenuService } from 'src/app/hmg-common/services/menu/menuservice.service';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { Device } from '@ionic-native/device/ngx';
import { attendanceSwipeScannerRequest } from './models/attendanceSwipe.Request';
import { Response } from 'src/app/hmg-common/services/models/response';
import { AttendanceService } from './services/attendance.services';
import { LoginRequest } from '../hmg-common/services/authentication/models/login.request';
import { FileUploaderComponent } from '../hmg-common/ui/file-uploader/file-uploader.component';
import { Camera } from '@ionic-native/Camera/ngx';
import { File } from '@ionic-native/file/ngx';
import { DomSanitizer } from '@angular/platform-browser';
import { SharedDataService } from '../hmg-common/services/shared-data-service/shared-data.service';
import { DevicePermissionsService } from '../hmg-common/services/device-permissions/device-permissions.service';
import { DashboredService } from '../hmg-common/services/dashbored/dashbored.service';
import { OrganizationSalariesResponse } from '../hmg-common/services/dashbored/organization-salaries.response';
import { OpenMissingSwipesResponse } from '../hmg-common/services/dashbored/open-missing-swipes.response';
import { PerformanceAppraisalResponse } from '../hmg-common/services/dashbored/performance-appraisal.response';
import { AttendanceTrackingResponse } from '../hmg-common/services/dashbored/attendance-tracking.response';
import { OpenPeriodDatesResponse } from '../hmg-common/services/dashbored/models/openPeriodDatesResponse';
import { GetSubordinatesAttdStatusRequest } from '../hmg-common/services/dashbored/models/GetSubordinatesAttdStatusRequest';
import { GetSubordinatesLeavesRequest } from '../hmg-common/services/dashbored/models/GetSubordinatesLeavesRequest';
import { GetOpenNotificationsResponse } from '../hmg-common/services/dashbored/models/GetOpenNotificationsResponse';
import { GetSubordinatesAttdStatusResponse } from '../hmg-common/services/dashbored/models/GetSubordinatesAttdStatusResponse';
import { GetSubordinatesLeavesResponse } from '../hmg-common/services/dashbored/models/GetSubordinatesLeavesResponse';
import { AccrualService } from '../accrual-balances/services/accrual.service';
import { TimeCardService } from '../time-card/service/time-card.service';
import { WorklistMainService } from '../notification/service/work-list.main.service';
import { isThisISOWeek } from 'date-fns';
import { Router } from '@angular/router';
import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx';
import { NFC, Ndef } from "@ionic-native/nfc/ngx"
import { DigitalIdComponent } from '../authentication/digital-id/digital-id.component';
import { FirebaseX } from '@ionic-native/firebase-x/ngx';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss']
})
export class HomePage implements OnInit {
  userData: any = {};
  userImage: any = '../assets/imgs/profile.png';
  menuList: any = [];
  zbarOptions: any;
  scannedResult: any;
  notBadge: any;
  lat: any;
  longt: any;
  deviceID: string;
  public maxFileSize = 10 * 1024 * 1024;
  public fileUploder: FileUploaderComponent;
  location: boolean;
  camera: boolean;
  ticketRequestObject: any;
  leaveRequestObject: any;
  missingSwipeRequestObject: any;
  public isShow = false;
  public showVcationRule = false;
  public isFakeLocationUsed = false;
  public intervalCountdown: any;
  public statsButtons = [
    {
      title: this.ts.trPK('attendance-tracking', 'title'),
      link: '0',
      show: true
    },
    {
      title: this.ts.trPK('home', 'worklist'),
      statsValue: 0,
      icon: 'assets/icon/new-design/work_list.png',
      link: '1',
      show: true
    },
    {
      title: this.ts.trPK('home', 'missing-swipes'),
      statsValue: 0,
      icon: 'assets/icon/new-design/missing_swipe.png',
      link: '2',
      show: true
    },
    {
      title: this.ts.trPK('home', 'leave-balance'),
      statsValue: 0,
      icon: 'assets/icon/new-design/leave_balance.png',
      link: '3',
      show: this.isShow,
    },
    {
      title: this.ts.trPK('absenceList', 'tickets-balance'),
      statsValue: 0,
      icon: 'assets/icon/new-design/ticket_balance.png',
      link: '4',
      show: this.isShow
    }
  ];

  public slideOptsOne = {};

  public slideOptsTwo = {};
  public runTimer = false;
  public hasStarted = false;
  public hasFinished = false;
  public remainingTime: any;
  public scheduledTime: any;
  public spentHours: any;
  public isCheckedIn = undefined;
  public displayTime: any;
  public menuEntries: any;
  public percent: any;
  public selEmp: string;
  public selMenu: MenuResponse = new MenuResponse();
  public respID: number;
  public menuType: any;
  accrualBalancesList: any;
  public countAllNotification = 0;
  myTeamTitle: string;
  vacationRuleTitle: string = this.ts.trPK('vacation-rule', 'vacationRule');
  public myTeamIcon: string;
  public vacationRuleIcon: string;
  direction: string;
  public isPostNoLoad = true;
  public showStaticServices = false;

  constructor(
    public ts: TranslatorService,
    public menu: MenuController,
    public authService: AuthenticationService,
    public menuService: MenuService,
    public common: CommonService,
    public events: Events,
    private device: Device,
    private geolocation: Geolocation,
    private attendanceService: AttendanceService,
    private eitService: EitService,
    private barcodeScanner: BarcodeScanner,
    public actionSheetCtrl: ActionSheetController,
    public sharedData: SharedDataService,
    private sanitizer: DomSanitizer,
    private file: File,
    private permissions: DevicePermissionsService,
    public DS: DashboredService,
    public accrualService: AccrualService,
    public timeCardService: TimeCardService,
    public workListService: WorklistMainService,
    public router: Router,
    private platform: Platform,
    public backgroundGeolocation: BackgroundGeolocation,
    public modalController: ModalController,
    private nfc: NFC,
    public firebasex: FirebaseX
  ) {
    this.events.subscribe('img-change', displayImg => {
      this.userImage = this.sanitizer.bypassSecurityTrustUrl(
        'data:Image/*;base64,' + displayImg
      );
    });
  }

  ngOnInit() {
    let openDigitalIDCard = this.sharedData.getSharedData("loginWithDigitalIDButton", true);
    this.direction = TranslatorService.getCurrentLanguageName();
    this.myTeamTitle = this.ts.trPK('myTeam', 'myTeam-header');
    this.vacationRuleTitle = this.ts.trPK('vacation-rule', 'vacationRule');
    this.common.startLoading();
    this.menu.enable(true);
    this.events.subscribe('getNotCount', badge => {
      this.notBadge = badge;
    });
    if (openDigitalIDCard === true) {
      console.log("DONE");
      this.openDigitalId();
    }
  }

  public slideSettingsTwo() {
    const width = this.platform.width();
    this.slideOptsOne = {
      slidesPerView: width > 320 ? 3.5 : 3,
      spaceBetween: 10
    };
    this.slideOptsTwo = {
        slidesPerView: width > 320 ? 3.2 : 2.5,
        spaceBetween: width > 320 ? 10 : 5
    };
    this.showStaticServices = true;
}
  ionViewWillEnter() {
    this.common.startLoading();
    this.slideSettingsTwo();
    this.common.sharedService.setSharedData(true, 'loadWorkList');
    this.remainingTime = 0;
    this.displayTime = '00:00:00';
    this.runTimer = false;
    this.getUserDetails();
  }

  initTimer() {
    this.runTimer = false;
    this.hasStarted = false;
    this.hasFinished = false;
    this.percent = 100 - (this.remainingTime / this.scheduledTime) * 100;
    this.displayTime = this.getSecondsAsDigitalClock(this.remainingTime);
    this.startTimer();
  }

  startTimer() {
    this.runTimer = true;
    this.hasStarted = true;
    this.timerTick();
  }

  timerTick() {
    this.intervalCountdown = setTimeout(() => {
      if (!this.runTimer) {
        return;
      }
      this.remainingTime--;
      this.displayTime = this.getSecondsAsDigitalClock(this.remainingTime);
      if (this.remainingTime > 0) {
        const newPercent: any = (
          (this.remainingTime / this.scheduledTime) *
          100
        ).toFixed(2);
        this.percent = 100 - newPercent;
        this.timerTick();
      } else {
        this.hasFinished = true;
      }
    }, 1000);
  }

  getSecondsAsDigitalClock(inputSeconds: number) {
    const secNum = parseInt(inputSeconds.toString(), 10); // don't forget the second param
    const hours = Math.floor(secNum / 3600);
    const minutes = Math.floor((secNum - hours * 3600) / 60);
    const seconds = secNum - hours * 3600 - minutes * 60;
    let hoursString = '';
    let minutesString = '';
    let secondsString = '';
    hoursString = hours < 10 ? '0' + hours : hours.toString();
    minutesString = minutes < 10 ? '0' + minutes : minutes.toString();
    secondsString = seconds < 10 ? '0' + seconds : seconds.toString();
    return hoursString + ':' + minutesString + ':' + secondsString;
  }

  getDeviceLocation() {
    const isVirtual = this.device.isVirtual;
    if (isVirtual === true) {
      alert('emulater>>>>>>>' + isVirtual);
      alert('You are using virtual device');
      return false;
    }
    this.permissions.requestLocationAutherization().then(granted => {
      this.location = granted as boolean;
      if (this.location) {
        if (this.platform.is('android')) {
          this.backgroundGeolocation.getCurrentLocation({ timeout: 10000, enableHighAccuracy: true, maximumAge: 3000 }).then((resp) => {
            if (resp && (resp.latitude && resp.longitude)) {
              if (resp.isFromMockProvider || resp.mockLocationsEnabled) {
                this.isFakeLocationUsed = true;
              }
              this.lat = resp.latitude;
              this.longt = resp.longitude;
              this.attendance();
            } else {
              this.common.presentAlert(this.ts.trPK('home', 'position-error'));
            }
          }, (error) => {
            this.common.presentAlert(this.ts.trPK('home', 'position-error'));
          });
        } else {
          this.geolocation.getCurrentPosition({ maximumAge: 3000, timeout: 10000, enableHighAccuracy: true }).then(resp => {
            if (resp && resp.coords.latitude && resp.coords.longitude) {
              this.lat = resp.coords.latitude;
              this.longt = resp.coords.longitude;
              this.attendance();
            } else {
              this.common.presentAlert(this.ts.trPK('home', 'position-error'));
            }
          }).catch(error => {
            this.common.presentAlert(this.ts.trPK('home', 'position-error'));
          });
        }
      } else {
        return false;
      }
    });
  }

  setServicesPrivilage() {
    for (const servicePrivilage of AuthenticationService.servicePrivilage) {
      if (servicePrivilage.Previlege === false) {
        if (servicePrivilage.ServiceName === 'accrualBalance') {
          this.statsButtons[3].show = false;
          this.statsButtons[4].show = false;
        }
        if (servicePrivilage.ServiceName === 'vacationRule') {
          this.showVcationRule = false;
        }
        // document
        //   .getElementById(servicePrivilage.ServiceName)
        //   .setAttribute('disabled', 'disabled');
        // document.getElementById(servicePrivilage.ServiceName).style.filter =
        //   'grayscale(1)';
      } else {
        this.statsButtons[3].show = true;
        this.statsButtons[4].show = true;
        this.showVcationRule = true;
      }
    }
  }

  // getCount() {
  // const req: any = {};
  // this.menuService.getNotificationCount(req).subscribe((result: any) => {
  //   if (this.common.validResponse(result)) {
  //     this.notBadge =
  //       result.GetOpenNotificationsNumList.P_OPEN_NOTIFICATIONS_NUM;
  //     if (this.notBadge <= 0) {
  //       this.notBadge = null;
  //     }
  //     this.events.publish("getNotCount", this.notBadge);
  //   }
  // });
  // }

  private openMenu() {
    this.menu.toggle();
  }

  private getUserDetails() {
    this.authService
      .loadAuthenticatedUser()
      .subscribe((user: AuthenticatedUser) => {
        if (user) {
          this.events.publish('setMenu');
          this.userData = user;
          this.sharedData.setSharedData(
            this.userData,
            AuthenticatedUser.SHARED_DATA
          );
          if (this.common.getUpdateImage().status) {
            this.userImage = this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,' + this.common.getUpdateImage().img);
          } else {
            this.userImage = user.EMPLOYEE_IMAGE
              ? 'data:image/png;base64,' + user.EMPLOYEE_IMAGE
              : this.userImage;
          }
          this.callDashboardServices();
        } else {
          console.log(user);
        }
      });
  }

  callDashboardServices() {
    this.getMenu();
    this.setServicesPrivilage();
    this.openNotificationsDashbored();
    this.showOpenMissingSwipes();
    this.showAttendanceTracking();
    this.getAccrualBalance();
  }

  public Vacation_Rule() {
    this.common.navigateForward('/vacation-rule/home');
  }

  private getMenu() {
    this.menuService.getMenu('', '', this.isPostNoLoad).subscribe((result: MenuResponse) => {
      this.handleMenuResult(result);
    });
  }

  private handleMenuResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.List_Menu)) {
        this.menuList = result.List_Menu;
        this.getMenuDetails();
      }
    }
  }

  private accrualBalance() {
    this.common.openAccuralPage();
  }

  private changeImage() {
    this.common.openChangeImagePage();
  }

  public getMenuDetails() {
    const item = this.menuList[0];
    const selMenu: MenuResponse = new MenuResponse();
    selMenu.List_Menu = item;
    selMenu.userid = this.userData.EMPLOYEE_NUMBER;
    this.common.sharedService.setSharedData(selMenu, MenuResponse.SHARED_DATA);
    this.getMenuEntries(item);
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < this.menuList.length; i++) {
      if (this.menuList[i].MENU_TYPE === 'M') {
        this.events.publish('myTeamFlag', 'true');
        //  this.common.sharedService.setSharedData('true', "myTeamFlag");
      }
    }

    // if (item.MENU_TYPE === 'M') {
    // this.common.openMyTeamPage();
    //   // this.navCtrl.push("MySubordinatePage");
    // } else if (item.MENU_TYPE === 'S') {
    //   this.common.sharedService.setSharedData(item, 'mySpecList');
    //   this.common.openMySpecialistPage();
    //   // this.navCtrl.push('MySpecialistPage',{"mySpecList":item});
    // } else {
    //   this.getMenuEntries(item);
    // }
  }

  openMyTeamPage() {
    this.common.openMyTeamPage();
  }

  openTimeCard() {
    this.common.openTimeCardPage();
  }

  getMenuEntries(item) {
    const request: any = {};
    let selEmpNo: string = null;
    let nationality: string = null;
    request.P_SELECTED_RESP_ID = -999;
    if (item.MENU_TYPE === 'S') {
      request.P_SELECTED_RESP_ID = item.RESP_ID;
    } else {
      selEmpNo = this.common.sharedService.getSharedData(
        LoginRequest.SHARED_DATA,
        false
      );
    }
    nationality = this.common.sharedService.getSharedData(
      LoginRequest.NATIONALITY_CODE,
      false
    );
    request.P_SELECTED_EMPLOYEE_NUMBER = selEmpNo;
    request.P_MENU_TYPE = item.MENU_TYPE;
    request.NationalityCode = nationality;
    // set emp and resp id
    this.common.sharedService.setSharedData(
      selEmpNo,
      MenuResponse.SHARED_SEL_EMP
    );
    this.common.sharedService.setSharedData(
      request.P_SELECTED_RESP_ID,
      MenuResponse.SHARED_SEL_RESP_ID
    );

    this.eitService
      .getMenuEntries(request, '', '', this.isPostNoLoad)
      .subscribe((result: MenuResponse) => {
        this.handleMenuEntiresResult(result);
      });
  }

  sortMenuEntires(list) {
    const tree = this.common.list_to_tree(list);
    this.menuEntries = tree;
    this.common.sharedService.setSharedData(tree, 'menuEntries');
    this.common.sharedService.setSharedData('home', 'homemenuentries');
    // this.common.navigateForward("/eit/homepage");
    // this.common.openEITPage();
  }

  private handleMenuEntiresResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.GetMenuEntriesList)) {
        // tslint:disable-next-line: prefer-for-of
        for (let i = 0; i < result.GetMenuEntriesList.length; i++) {
          // tslint:disable-next-line: triple-equals
          if (result.GetMenuEntriesList[i].FUNCTION_NAME == 'HMG_TKT_NEW_EIT_SS') {
            this.ticketRequestObject = result.GetMenuEntriesList[i];
            // tslint:disable-next-line: triple-equals
          } else if (result.GetMenuEntriesList[i].FUNCTION_NAME == 'HR_LOA_SS') {
            this.leaveRequestObject = result.GetMenuEntriesList[i];
            // tslint:disable-next-line: triple-equals
          } else if (result.GetMenuEntriesList[i].FUNCTION_NAME == 'HMG_OTL_MISSING_SWIPE_EIT_SS') {
            this.missingSwipeRequestObject = result.GetMenuEntriesList[i];
          }
        }
        this.sortMenuEntires(result.GetMenuEntriesList);
      }
    }
  }

  parentFn($event: string) {
    console.log($event);
  }

  private Change_password() {
    this.common.openChangePassword();
  }

  private openPayslip() {
    this.common.openPayslipPage();
  }

  private attendance() {
    this.permissions.requestCameraAutherization().then(granted => {
      this.camera = granted as boolean;
      if (this.camera) {
        this.scanCode();
      }
    });
  }

  scanCode() {
    this.barcodeScanner
      .scan()
      .then(barcodeData => {
        if (!barcodeData.cancelled) {
          this.scannedResult = barcodeData;
          this.deviceID = this.device.uuid;
          if (this.isFakeLocationUsed) {
            this.fakeSwipeAttendance();
          } else {
            this.swipeAttendance();
          }
        }
      })
      .catch(err => {
        console.log('Error', err);
      });
  }

  fakeSwipeAttendance() {
    const request: any = {};
    request.Latitude = this.lat;
    request.Longitude = this.longt;
    request.QRValue = this.scannedResult.text;
    request.UID = this.deviceID;
    request.EmployeeID = this.userData.EMPLOYEE_NUMBER;
    this.attendanceService.fakeAttendanceSwipeScanner(request, () => { console.log('Error inside in swipe attendance'); })
      .subscribe((result: Response) => {
        if (this.common.validResponse(result)) {
          this.common.presentAlert(this.ts.trPK('home', 'fake-location'));
        }
      });
  }

  swipeAttendance() {
    const request: attendanceSwipeScannerRequest = new attendanceSwipeScannerRequest();
    request.Latitude = this.lat;
    request.Longitude = this.longt;
    request.QRValue = this.scannedResult.text;
    request.UID = this.deviceID;
    request.UserName = this.userData.EMPLOYEE_NUMBER;
    this.attendanceService
      .attendanceSwipeScanner(request, () => {
        console.log('Error inside in swipe attendance');
      })
      .subscribe((result: Response) => {
        if (this.common.validResponse(result)) {
          this.common.presentAlert(this.ts.trPK('home', 'swipeAlertSuccess'));
          this.showAttendanceTracking();
        }
      });
  }

  openPersonalInfo() {
    this.common.openProfile('sideMenu');
  }

  // Dashboard Services
  showOrganizationSalaries() {
    this.DS.getOrganizationSalaries().subscribe(
      (result: OrganizationSalariesResponse) => { }
    );
  }

  showOpenMissingSwipes() {
    this.DS.getOpenMissingSwipes('', '', this.isPostNoLoad).subscribe(
      (result: OpenMissingSwipesResponse) => {
        if (this.common.validResponse(result)) {
          const key = 'GetOpenMissingSwipesList';
          this.statsButtons[2].statsValue = Math.floor(result[key].P_OPEN_MISSING_SWIPES);
        }
      }
    );
  }

  showPerformanceAppraisal() {
    this.DS.getPerformanceAppraisal().subscribe(
      (result: PerformanceAppraisalResponse) => { }
    );
  }

  convertInSeconds(time: any) {
    const hours = parseInt(time[0], 10);
    const minutes = parseInt(time[1], 10);
    let seconds = parseInt(time[2], 10);
    seconds = seconds + hours * 60 * 60 + minutes * 60;
    return seconds;
  }

  convertAndAssignTime(data) {
    this.remainingTime = this.convertInSeconds(data.P_REMAINING_HOURS.split(':'));
    this.scheduledTime = this.convertInSeconds(data.P_SCHEDULED_HOURS.split(':'));
    this.spentHours = this.convertInSeconds(data.P_SPENT_HOURS.split(':'));
    this.isCheckedIn = this.spentHours === 0 ? false : true;
    if (this.isCheckedIn && this.remainingTime != 0) {
      this.initTimer();
    } else if (this.isCheckedIn && this.remainingTime === 0) {
      this.percent = 100;
    }
  }

  showAttendanceTracking() {
    const request = {
      P_SELECTED_EMPLOYEE_NUMBER: this.userData.EMPLOYEE_NUMBER
    };
    this.DS.getAttendanceTracking(request, '', '', this.isPostNoLoad).subscribe((result: AttendanceTrackingResponse) => {
      if (this.common.validResponse(result)) {
        clearTimeout(this.intervalCountdown);
        const key = 'GetAttendanceTrackingList';
        this.convertAndAssignTime(result[key]);
      }
    });
  }

  openPeriodDateDashbored() {
    this.DS.getOpenPeriodDates(() => { console.log('Error '); }).subscribe((result: OpenPeriodDatesResponse) => {
      if (this.common.validResponse(result)) {
        console.log('response');
      }
    });
  }

  openNotificationsDashbored() {
    this.DS.getOpenNotifications('', '', false).subscribe((result: GetOpenNotificationsResponse) => {
      if (this.common.validResponse(result)) {
        const key = 'P_OPEN_NTF_NUMBER';
        this.countAllNotification = result[key];
        this.ITGCountAllNotification();
        this.common.sharedService.setSharedData(
          result,
          'worklistNotifications'
        );
      }
    });
  }

  ITGCountAllNotification() {
    this.workListService.getITGDetails('', '', this.isPostNoLoad).subscribe((result: any) => {
      this.statsButtons[1].statsValue =
        Math.floor(this.countAllNotification + result.TotalCount);
      this.common.stopLoading();
    });
  }

  getSubordinatesLeaves() {
    const request: GetSubordinatesLeavesRequest = new GetSubordinatesLeavesRequest();
    request.P_DATE_FROM = '/Date(1578603600000+0300)/'; // test
    request.P_DATE_TO = '/Date(1576011600000+0300)/'; // test
    this.DS.getSubordinatesLeaves(request, () => {
      console.log('Error ');
    }).subscribe((result: GetSubordinatesLeavesResponse) => {
      if (this.common.validResponse(result)) {
        console.log('response');
        console.log(result);
      }
    });
  }

  getSubordinatesAttStatus() {
    const request: GetSubordinatesAttdStatusRequest = new GetSubordinatesAttdStatusRequest();
    request.P_SCHEDULE_DATE_FROM = '/Date(1578603600000+0300)/'; // test
    request.P_SCHEDULE_DATE_TO = '/Date(1576011600000+0300)/'; // test
    this.DS.getSubordinatesAttStatus(request, () => {
      console.log('Error ');
    }).subscribe((result: GetSubordinatesAttdStatusResponse) => {
      if (this.common.validResponse(result)) {
        console.log('response');
        console.log(result);
      }
    });
  }

  openPage(subMenu) {
    console.log(subMenu);
    let selMenu: MenuResponse = new MenuResponse();
    selMenu = this.common.sharedService.getSharedData(
      MenuResponse.SHARED_DATA,
      false
    );
    selMenu.GetMenuEntriesList = subMenu;
    this.common.sharedService.setSharedData(selMenu, MenuResponse.SHARED_DATA);
    if (subMenu.REQUEST_TYPE === 'ABSENCE') {
      this.common.openAbsencePage();
    } else if (subMenu.REQUEST_TYPE === 'EIT') {
      this.common.openEitListPage();
    } else if (subMenu.REQUEST_TYPE === 'PAYSLIP') {
      this.common.openPayslipPage();
    } else if (subMenu.MENU_ENTRY_TYPE === 'MENU') {
      this.common.sharedService.setSharedData(
        selMenu.GetMenuEntriesList,
        'menuEntries'
      );
      this.common.openEITPage();
    }
    if (subMenu.REQUEST_TYPE === 'TIME_CARD') {
      this.common.openTimeCardPage();
    }
  }

  getAccrualBalance() {
    const today = new Date();
    const day = today.getDate();
    const month = today.getMonth() + 1;
    const year = today.getFullYear();
    const todayDate = month + '/' + day + '/' + year;
    const effectiveDate = todayDate;
    const request = {
      P_SELECTED_EMPLOYEE_NUMBER: this.userData.EMPLOYEE_NUMBER,
      P_EFFECTIVE_DATE: effectiveDate
    };
    this.accrualService.getAccrualBalances(request, '', '', this.isPostNoLoad).subscribe((result: any) => {
      if (this.common.validResponse(result)) {
        let totalTicketsLeft = 0;
        this.accrualBalancesList = result.GetAccrualBalancesList;
        for (const accrualBalance of result.GetAccrualBalancesList) {
          if (accrualBalance.ACCURAL_PLAN_NAME === 'HMG Annual Vacation Accrual Plan') {
            this.statsButtons[3].statsValue = accrualBalance.ACCRUAL_NET_ENTITLEMENT === null ? 0 : Number(accrualBalance.ACCRUAL_NET_ENTITLEMENT.toFixed(2));
            this.common.sharedService.setSharedData(accrualBalance, 'leaveAccrualBalance');
            this.common.sharedService.setSharedData(request, 'leaveAccrualBalanceDate');
            this.common.sharedService.setSharedData(this.accrualBalancesList, 'tickitsbalance');
          } else {
            totalTicketsLeft = totalTicketsLeft + accrualBalance.ACCRUAL_NET_ENTITLEMENT;
          }
        }
        this.statsButtons[4].statsValue = Number(totalTicketsLeft.toFixed(2)); 
      }
    });
  }

  openattentracking() {
    this.common.openAttenTrackingpage();
  }

  public showAttendanceOptions() {
    this.common.openAttendanceOptionsComponent();
  }

  openStatsButton(link: any) {
    // tslint:disable-next-line: triple-equals
    if (link == '0') {
      this.isFakeLocationUsed = false;
      // this.getDeviceLocation();
      this.showAttendanceOptions();
      // tslint:disable-next-line: triple-equals
    } else if (link == '1') {
      this.common.startLoading();
      this.common.openNotificationPage();
      // tslint:disable-next-line: triple-equals
    } else if (link == '2') {
      this.openPage(this.missingSwipeRequestObject);
      // tslint:disable-next-line: triple-equals
    } else if (link == '3') {
      this.openPage(this.leaveRequestObject);
      // tslint:disable-next-line: triple-equals
    } else if (link == '4') {
      this.openPage(this.ticketRequestObject);
    }
  }

  async openDigitalId() {
    const modal = await this.modalController.create({
      component: DigitalIdComponent,
      cssClass: 'digital-id-modal-css'
    });
    return await modal.present();
  }
  itemForSale() {
    this.common.navigateForward('/itemforsale/items');
  }
  offersDiscount() {
    this.common.navigateForward('/offersdiscount/home');
  }
  openAnnouncement() {
    this.common.openAnnouncement();
  }
}
