import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  RouterStateSnapshot,
  Router,
  UrlTree,
} from '@angular/router';
import { USERInterface } from '../interfaces/user-interface';
import { ENCService } from '../services/enc/enc.service';

@Injectable({
  providedIn: 'root',
})
export class LoginGuard implements CanActivate {
  empresas_arr: any[] = [];
  constructor(private router: Router, private _encService: ENCService) {
    this.empresas_arr = [
      {
        RFC: "TME700618RC7",
        NOMBRE: "TIMKEN" 
      },

    ]
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    const url: string = state.url;
    let isLoggedIn = localStorage.getItem('jwt') != null;

    if( localStorage.getItem('TIMUSERENC') != "undefined"){
      let usuario: USERInterface = JSON.parse(
        localStorage.getItem('TIMUSERENC')!
      );
  
      const redirectUrl = '/mesmpr';
  
      //TIMRFC
      if (
        localStorage.getItem('RFCEMPRESA') != '' ||
        localStorage.getItem('RFCEMPRESA') != undefined ||
        localStorage.getItem('RFCEMPRESA') != "undefined" ||
        localStorage.getItem('RFCEMPRESA') != null
      ) {
        if (window.location.href.includes('?')) {
          let rfc_array = window.location.href.split('?')[1].split('/')[0];
          localStorage.setItem('RFCEMPRESA', rfc_array);
          
          let empresa:any = this.empresas_arr.filter(element => element.NOMBRE == rfc_array.toUpperCase());
          if (empresa.length > 0) {
            localStorage.setItem("RFCEMPRESA", empresa[0].RFC);
          }else{
            localStorage.setItem("RFCEMPRESA", "ITTEC");
          }

        } else if (localStorage.getItem('RFCEMPRESA') == 'TME700618RC7') {
          localStorage.setItem('RFCEMPRESA', 'TME700618RC7');
        } else {
          localStorage.setItem('RFCEMPRESA', 'ITTEC');
        }
      } else {
        localStorage.setItem('RFCEMPRESA', 'ITTEC');
      }
  
      if (isLoggedIn && usuario != null) {
        this.router.navigate([redirectUrl]);
        return false;
      }
      return true;
    }else{
      localStorage.removeItem('TIMUSERENC');
      localStorage.removeItem('jwt');
      return true;
    }
    
  }
}
