import { ValidToken } from './../../interfaces/valid-token.interface';
import { LoginService } from 'src/app/services/login/login.service';
import { SocketService } from './../socket.service';
import { ConnectionsService } from './../connections.service';
import { interval, lastValueFrom, take } from 'rxjs';
import { ModulesService } from './../modules.service';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { EncService } from '../enc/enc.service';
import { GeolocationService } from '@ng-web-apis/geolocation';

@Injectable({
  providedIn: 'root'
})
export class LoginDataService {
  public localStorageLogin

  constructor(
    private router: Router,
    private _encService: EncService,
    private _connectionsServiece: ConnectionsService,
    private _socketService: SocketService,
    private _loginService: LoginService,
    private readonly geolocation$: GeolocationService,
  ) {
    this.localStorageLogin = localStorage
  }

  saveLoginInformation(token: string, idusuario: string, nombre_usuario: string, correo: string, perfil: string, permisos: string) {
    this.localStorageLogin.setItem('token', token)
    this.localStorageLogin.setItem('idusuario', idusuario)
    this.localStorageLogin.setItem('nombre_usuario', nombre_usuario)
    this.localStorageLogin.setItem('correo', correo)
    this.localStorageLogin.setItem('permisos', permisos)
    this.localStorageLogin.setItem('perfil', perfil)
  }

  async verifyToken(token: string): Promise<boolean>{
    try{
      let resp: ValidToken = await lastValueFrom(this._loginService.verifyToken(token));

      if(resp.error){
        return false;
      }else{
        return resp.response.validToken;
      }
    }catch(error: any){
      return false;
    }
  }

  showToken() {
    return this.localStorageLogin.getItem('token')
  }

  showIdusuario() {
    return this.localStorageLogin.getItem('idusuario')
  }

  showPerfil() {
    return this.localStorageLogin.getItem('perfil')
  }

  showNombreUsuario() {
    return this._encService.desencriptar(this.localStorageLogin.getItem('nombre_usuario')!)
  }

  showCorreo() {
    return this._encService.desencriptar(this.localStorageLogin.getItem('correo')!)
  }

  logout () {
    this.geolocation$.pipe(take(1)).subscribe(position => {
      let userPosition = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        accuracy: position.coords.accuracy
      };

      let userPositionStr = JSON.stringify(userPosition);
      this.requestLogout(userPositionStr);
    });
  }

  async requestLogout(position: string){
    let id = localStorage.getItem('idusuario');

    try{
      await lastValueFrom(this._connectionsServiece.setLastConnection({
        id: id,
        linea: 1,
        lugarConexion: position
      }));
  
      this._socketService.unregister(id!);
      this.localStorageLogin.clear()
      this.router.navigate(['login']);

    }catch(error: any){
      this._socketService.unregister(id!);
      this.localStorageLogin.clear()
      this.router.navigate(['login']);
    }
  }

  isLogin () {
    return this.localStorageLogin.getItem('token') != '' && this.localStorageLogin.getItem('token') != undefined && this.localStorageLogin.getItem('token') != null
  }

}
