import { HttpClient } from '@angular/common/http';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Globals } from '../../../services/globals';
import { AuthorizeService } from '../../../services/authorize.service';
import { ServerInfoService } from '../../../services/serverinfo.service';
import { now } from '../../../utils';

const
  second = 1000,
  minute = second * 60,
  hour = minute * 60,
  day = hour * 24;

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.scss']
})

export class FooterComponent implements OnInit, OnDestroy {
  counter: any;

  days: number;
  hours: number;
  mins: number;
  secs: number;
  public package_json;
  public coreVersion: string;
  public devextremeVersion: string;

  constructor(
    public globals: Globals,
    public serverInfoService: ServerInfoService,
    public authService: AuthorizeService,
    private http: HttpClient
  ) {
    this.counter = setInterval(() => this.updateTimer(), 1000);
  }

  updateTimer = () => {
    if (!this.authService.useJWT || !this.authService.HR_JWT) return;
    let distance = this.authService.HR_JWT?.expiresAt?.valueOf() - now();
    if (distance < -3 * second) return;
    if (distance < 0) distance = 0;

    this.days = Math.floor(distance / day);
    this.hours = this.days > 0 ? 0 : Math.floor((distance % day) / hour);
    this.mins = this.days > 0 || this.hours > 1 ? 0 : Math.floor((distance % hour) / minute);
    this.secs = this.days > 0 || this.hours > 0 || this.mins > 1 ? 0 : Math.floor((distance % minute) / second);
  }

  ngOnInit() {
    this.http.get('../../../assets/json/package.json').subscribe((data) => {
      this.package_json = data;
      this.coreVersion = this.package_json?.version;
      this.devextremeVersion = !this.package_json?.peerDependencies || !this.package_json?.peerDependencies['devextreme-angular'] ? undefined : this.package_json?.peerDependencies['devextreme-angular']
      this.devextremeVersion = this.devextremeVersion ?? this.package_json?.dependencies['devextreme-angular'];
    });
  }

  ngOnDestroy(): void {
    clearInterval(this.counter);
  }
}
