import { Component } from '@angular/core';
import { Router } from '@angular/router';
import swal from 'sweetalert';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'DVR Report';
  timer: any;
  tokenExpirationTimer:any;

  
  ngOnDestroy() {
    this.timer.clear();
  }

  constructor(private router: Router) {
    this.loadJS("../assets/js/jquery-ui.js");
    this.loadJS("../assets/js/bootstrap.min.js");


    this.loadCSS("../assets/css/dataTables.jqueryui.css");

    this.loadCSS("../assets/css/bootstrap.min.css");

    this.loadCSS("../assets/css/font-awesome.min.css");

    this.loadCSS("../assets/css/style.css");
  }

  ngOnInit() {

    if(localStorage.getItem("loginData")){
      //const timeToLogout =  new Date().getTime();
      this.autoLogout(3600000);
    //  console.log("timeToLogout ::" + timeToLogout);
    }
 
  }


  autoLogout(expirateionDuration: number) {

    expirateionDuration = expirateionDuration ;
    console.log("expirateionDuration:::", expirateionDuration)
    this.tokenExpirationTimer = setTimeout(() => {

      swal({
        title: "Session Timeout!",
        text: "You're being timed out due to inactivity.",
        buttons: {
          
          cancel: {
            text: "Log Out",
            value: false,
            visible: true,
            className: "swal-button--danger",
            closeModal: true
          },
        },
        // dangerMode: true,
        closeOnClickOutside: false,
        closeOnEsc: false,
        timer: 170000,
      })
        .then((willDelete: any) => {
          console.log((willDelete))
          if (!willDelete) {
            swal("You were Logged out!", {
              icon: "success",
              closeOnClickOutside: false,
              closeOnEsc: false
            });
            this.router.navigate(['/login'])
          } else {
           
            swal("You are safe!", {
              closeOnClickOutside: false,
              closeOnEsc: false
            });
          }
        });
    }
      ,
      expirateionDuration);


  }

  loadJS(url) {
    // console.log("JS file loaded successfully: " + url);
    return new Promise((resolve, reject) => {
      var e = document.createElement("script");
      e.src = url;
      e.type = "text/javascript";
      // e.addEventListener('load', callback);
      document.getElementsByTagName("head")[0].appendChild(e);
      resolve(true);
      // console.log("Js loaded");
    });
  }

  loadCSS(url) {
    // Create link
    // console.log("in sstratrytafcvkjab");
    let link = document.createElement('link');
    link.href = url;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    document.head.appendChild(link);

  }
}
