import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  RouterStateSnapshot,
  Router,
  UrlTree,
} from '@angular/router';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { USERInterface } from '../interfaces/user-interface';
import { ENCService } from '../services/enc/enc.service';
import { IAMService } from '../services/iam/iam.service';
import { MCOMAUService } from '../services/mco/mcomau/mcomau.service';
import { WebSocketService } from '../services/socket/web-socket.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  jwt: Observable<string[]> = {} as Observable<string[]>;
  private _docSub: Subscription = {} as Subscription;

  private empresas_arr :any[] = [];

  constructor(
    private _IAMService: IAMService,
    private _encService: ENCService,
    private router: Router,
    private _snackBar: MatSnackBar,
    private webSocketService: WebSocketService,
    private _mcomauService: MCOMAUService
  ) {

   
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<true | UrlTree> {
    const url: string = state.url;

    return this.checkLogin(url);
  }

  async checkLogin(url: string): Promise<true | UrlTree> {
    
    const sleep = (ms:number) => new Promise(resolve => setTimeout(resolve, ms));



    let bloq = false;
    this.webSocketService.emit('localstorage_update', localStorage);
    this.webSocketService.listen('localstorage_error').subscribe(async (res: any) => {  
      if (res.error) {
        bloq = true;
        this._IAMService.logout();
        this._snackBar.open(res.msj, 'Cerrar');
      }
    });
    await sleep(100);
    
    //Obtener boolean
    let isLoggedIn = localStorage.getItem('jwt') != null;

    if (isLoggedIn && !bloq ) {
      return true;
    }
    // Store the attempted URL for redirecting
    this._IAMService.redirectUrl = url;
    // Redirect to the login page
    return this.router.parseUrl('/iam');
  }


  async checkLocalStorage(){
    const sleep = (ms:number) => new Promise(resolve => setTimeout(resolve, ms))
    let bloq = false;
    
    this.webSocketService.emit('localstorage_update', localStorage);
    this.webSocketService.listen('localstorage_error').subscribe(async (res: any) => {
      if (res.error) {
        let bloq  = true;
        

        localStorage.removeItem('RFCEMPRESA');
        localStorage.removeItem('jwt');
        localStorage.removeItem('TIMUSERENC');
        
        await sleep(1000);

        localStorage.setItem('RFCEMPRESA', res.response.RFCEMPRESA);
        localStorage.setItem('TIMUSERENC', res.response.TIMUSERENC);
        localStorage.setItem('jwt', res.response.JWT);

        let TIMUSERENC: USERInterface = JSON.parse(res.response.TIMUSERENC);
        
         let bloq_user = {
          numero_empleado: this._encService.desencriptar(TIMUSERENC.IDUSUARIO),
          numero_empleado_modifica: this._encService.desencriptar(TIMUSERENC.IDUSUARIO)
        };
        
        this._mcomauService.bloquear(bloq_user);

        await sleep(1000);
        this._IAMService.logout();

        this._snackBar.open(res.msj, 'Cerrar');
        
      }
    });

    return bloq;
  }
}
