import { Injectable, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { ResponseLogin } from 'src/app/interfaces/iam/response-login';
import { IAMInterface } from 'src/app/interfaces/iam/iam-interface';
import { ENCService } from '../enc/enc.service';
import { WebSocketService } from '../socket/web-socket.service';
import { ResponseData } from 'src/app/interfaces/response-data';
import { LocalstorageService } from '../localstorage.service';
import { AuthGuard } from 'src/app/auth/auth.guard';
import { AdminGuard } from 'src/app/auth/admin.guard';
import { UserGuard } from 'src/app/auth/user.guard';

@Injectable({
  providedIn: 'root',
})
export class IAMService implements OnInit {
  private _url = 'https://qasirh.ittec.mx/v1/public/api';
  header: HttpHeaders = new HttpHeaders();
  current_user: string = '';
  jwt: string = '';

  constructor(
    private http: HttpClient,
    private _snackBar: MatSnackBar,
    private router: Router,
    private _encService: ENCService,
    private webSocketService: WebSocketService,
    public setUserStorage: LocalstorageService,
    private adminGuard: AdminGuard,
    private userGuard: UserGuard
  ) {
    this.getIPAddress();
  }
  ngOnInit(): void {}

  public usuario_rfc: string = '';
  public redirectUrl: string | null = null;
  private ipAddress: string = '';

  async login(data: IAMInterface, solicitud_datos: string) {
    if (this.ipAddress != '') {
      let objeto = {
        email: data.email.trim(),
        password: data.password.trim(),
        ip_address: this.ipAddress,
      };

      let respuesta = this.http
        .post<ResponseLogin>(`${this._url}/login`, objeto)
        .toPromise();
      await respuesta.then(
        async (data) => {
          if (!data?.error) {
            let status = this._encService.desencriptar(data!.response.ESTATUS);
            let perfil = this._encService.desencriptar(data!.response.PERFIL);
            let rfc_empresa = this._encService.desencriptar(
              data!.response.RFCEMPRESA
            );

            if (rfc_empresa == localStorage.getItem('RFCEMPRESA')) {
              switch (status) {
                case 'Activo':
                  
                  this.current_user = JSON.stringify(data!.response);
                  this.jwt = data!.response.TOKEN;
                  
                  localStorage.setItem('jwt', data!.response.TOKEN);
                  localStorage.setItem('TIMUSERENC',JSON.stringify(data?.response));
                  this.userType(perfil, solicitud_datos);

                  break;
                case 'Eliminado':
                  this.snackAlert('El usuario no existe');
                  break;
                case 'Inactivo':
                  this.snackAlert('El usuario esta bloqueado');
                  break;
                default:
                  this.snackAlert('Usuario inexistente');
                  break;
              }
            } else {
              this.snackAlert(
                'El R.F.C. del usuario no coincide con el R.F.C. del sistema al que desea entrar'
              );
            }
          } else {
            this.snackAlert(data.msg);
          }
        },
        (error) => {
          if (!error.ok) {
            this.snackAlert('Ocurrió un error inesperado');
          }
          if (error.error.msg != undefined) {
            this.snackAlert(error.error.msg);
          }
          if (error.status == 408) {
            this.snackAlert('Conexion lenta');
          }
        }
      );
    }
  }

  private snackAlert(mensaje: string) {
    this._snackBar.open(mensaje, 'Cerrar', {
      duration: 4000,
    });
  }

  private getIPAddress() {
    this.http.get('https://api.ipify.org?format=json').subscribe(
      (res: any) => {
        this.ipAddress = res.ip;
      },
      (error) => {
        if (!error.ok) {
          this.snackAlert('Ocurrió un error inesperado');
        }
        if (error.status == 408) {
          this.snackAlert('Conexion lenta');
        }
      }
    );
  }

  public logout(): void {
    clearInterval(this.adminGuard.aux_test);
    clearInterval(this.userGuard.aux_test);
    let rfc = localStorage.getItem('RFCEMPRESA');
    if (rfc === null || rfc === undefined || rfc === '') {
      localStorage.setItem('RFCEMPRESA', 'ITTEC');
    }
    localStorage.removeItem('jwt');
    localStorage.removeItem('TIMUSERENC');

    this.router.navigate(['/iam']);
    this.snackAlert('¡Hasta pronto!');
  }

  private userType(perfil: string, solicitud_datos: string) {
    
    if (perfil == "1") {
      if (solicitud_datos == '') {
        this.router.navigate(['/admin/mesmpr']);
      } else {
        this.router.navigate([
          '/admin/mesmav',
          {
            solicitud_datos: solicitud_datos,
          },
        ]);
      }
    } else {
      if (solicitud_datos == '') {
        this.router.navigate(['/mesmpr']);
      } else {
        this.router.navigate([
          '/mesmav',
          {
            solicitud_datos: solicitud_datos,
          },
        ]);
      }
    }
  }

  getJWT() {
    return this.jwt;
  }

  getCurrentUser() {
    return this.current_user;
  }

  getRFCEmpresa() {
    return this._encService.desencriptar(
      JSON.parse(this.current_user).RFCEMPRESA
    );
  }
}
