import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { DashboredService } from 'src/app/hmg-common/services/dashbored/dashbored.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import {AttendScanService} from '../../hmg-common/services/attend-services/attend-scan.service';
import { AttendanceTrackingResponse } from 'src/app/hmg-common/services/dashbored/attendance-tracking.response';
import { SharedDataService } from '../../hmg-common/services/shared-data-service/shared-data.service';
import { AuthenticatedUser } from 'src/app/hmg-common/services/authentication/models/authenticated-user';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  attendanceTrackingList: any = [];
  curentDate: any;
  direction: string;
  isCheckOut = false;
  public runTimer = false;
  public hasStarted = false;
  public hasFinished = false;
  public remainingTime: any;
  public scheduledTime: any;
  public isCheckedIn = undefined;
  public displayTime: any;
  public percent: any;
  public spentHours: any;
  public userData = this.sharedData.getSharedData(AuthenticatedUser.SHARED_DATA, false);
  constructor(
    public cs: CommonService,
    public db: DashboredService,
    public ts: TranslatorService,
    public attendScanService: AttendScanService,
    public sharedData: SharedDataService
  ) { }

  ngOnInit() {
    this.showAttendanceTracking();
    this.curentDate = new Date();
    this.direction = TranslatorService.getCurrentLanguageName();
    this.curentDate = this.getHeaderDate(this.curentDate);
  }

  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() {
    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;
  }

  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.displayTime = '00:00:00';
      this.percent = 100;
    }
}

  showAttendanceTracking() {
    const request = {
      P_SELECTED_EMPLOYEE_NUMBER: this.userData.EMPLOYEE_NUMBER
    };
    this.db.getAttendanceTracking(request).subscribe((result: AttendanceTrackingResponse) => {
      if (this.cs.validResponse(result)) {
        const key = 'GetAttendanceTrackingList';
        this.convertAndAssignTime(result[key]);
        this.attendanceTrackingList = result[key];
      }
    });
  }

  getHeaderDate(date: any) {
    if (this.direction === 'en') {
        return  this.cs.getMonthName(date.getMonth() + 1) + ', ' + date.getDate() + ' ' + date.getFullYear();
    } else {
        return  this.cs.getMonthNameAr(date.getMonth() + 1) + ', ' + date.getDate() + ' ' + date.getFullYear();
    }
}


  openDialog() {
    // this.cs.confirmAlertDialogAttendance(() => {
    //   this.attendScanService.getDeviceLocation();
    //   }, this.ts.trPK('general', 'ok'),
    //   () => {}, this.ts.trPK('general', 'cancel'),
    //   this.ts.trPK('vacation-rule', 'confirmation'),
    //   this.ts.trPK('attendance-tracking', 'confirm-alert1'));
    this.cs.openAttendanceOptionsComponent();
  }
}
