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';

@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
  ) {
    this.getIPAddress();
    this.checkSession();
  }
  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,
        password: data.password,
        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;

                  let jwt_local = localStorage.getItem('jwt');
                  let TIMUSERENC_local = localStorage.getItem('TIMUSERENC');

                  if (
                    (TIMUSERENC_local != '' ||
                      TIMUSERENC_local != undefined ||
                      TIMUSERENC_local != 'undefined' ||
                      TIMUSERENC_local != null) &&
                    (jwt_local != '' ||
                      jwt_local != undefined ||
                      jwt_local != 'undefined' ||
                      jwt_local != null)
                  ) {
                    localStorage.setItem('jwt', data!.response.TOKEN);
                    localStorage.setItem(
                      'CORREO',
                      this._encService.desencriptar(data!.response.CORREO)
                    );
                    localStorage.setItem(
                      'TIMUSERENC',
                      JSON.stringify(data!.response)
                    );

                    this.webSocketService.emit(
                      'localstorage_login',
                      localStorage
                    );
                    this.webSocketService
                      .listen('localstorage_login_error')
                      .subscribe((res: any) => {
                        if (res?.error) {
                          this.snackAlert(res.msj);
                        } else {
                          this.snackAlert(
                            'Bienvenido(a) ' + data?.response.NOMBRE!
                          );
                          this.userType(perfil, solicitud_datos);
                        }
                      });
                  } else {
                    this.snackAlert(
                      'Ya existe una sesión, cierra la sesión para continuar'
                    );
                  }

                  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 {
    this.usuario_rfc = localStorage.getItem('RFCEMPRESA')!;

    this.webSocketService.emit('localstorage_logout', '');

    localStorage.removeItem('RFCEMPRESA');
    localStorage.setItem('RFCEMPRESA', this.usuario_rfc);
    localStorage.removeItem('jwt');
    localStorage.removeItem('TIMUSERENC');

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

  private userType(perfil: string, solicitud_datos: string) {
    console.log(solicitud_datos);
    
    if (perfil == 'Administrador') {
      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,
          },
        ]);
      }
    }
  }

  checkSession() {
    /*  const bc = new BroadcastChannel('my-awesome-site');

    bc.onmessage = (event) => {
      if (event.data === 'Am I the first?') {
        bc.postMessage(`No you're not.`);
        alert('Another tab of this site just got opened');
      }
      if (event.data === `No you're not.`) {
        alert('An instance of this site is already running');
        this.router.navigate([
          '/duplicate-page',
        ]);
      }
    };

    bc.postMessage('Am I the first?'); */
  }

  getJWT() {
    return this.jwt;
  }

  getCurrentUser() {
    return this.current_user;
  }

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