import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AgenteAuth } from '../interfaces/agente.interface';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private baseUrl: string = "http://localhost:8080/agentes-auth";

  private _agenteAuth: AgenteAuth | undefined;
  private usuario: string='';
  private passsword: string='';
  agentesAuth: AgenteAuth[] = []

  constructor(private http: HttpClient) { 
    this.getAgentesAuth().subscribe(
      res => {
        console.log(res);
        this.agentesAuth = res;
      }
    )
  }
  
  get auth(): AgenteAuth {
    return {...this._agenteAuth!}
  }

  verificarAuth(): Observable<boolean> | boolean{
    if(!localStorage.getItem('usuario')){
      return false;
    }
    return true;
  }

  login(usuario: string, password: string): AgenteAuth{
    this.getAgentesAuth().subscribe(
      res => {
        this.agentesAuth = res;
      }
    )
    this.agentesAuth.filter(data =>{
      if(data.usuario==usuario && data.password==password){
        this.usuario=data.usuario;
        this.passsword=data.password;
        this._agenteAuth = data;
        localStorage.setItem('usuario', data.usuario);
        localStorage.setItem('rol', data.rol);
        if(data.rol!="supervisor"){
          localStorage.setItem('id', data.agenteReservas[0].id.toPrecision());
        }
      }
    });
    return this._agenteAuth!;
  }

  logout(){
    localStorage.removeItem('usuario');   
    localStorage.removeItem('rol');
    localStorage.removeItem('id');
    this._agenteAuth = undefined;
  }

  public getUserRole(){
    return localStorage.getItem('rol');
  }

  getAgentesAuth(): Observable<any[]>{
    return this.http.get<any[]>(`${ this.baseUrl }/listar`);
  }

  addAgenteAuth(query:any): Observable<any> {
    return this.http.post(this.baseUrl+"/agregar",query);
  }

}
