import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { AgentesService } from '../../services/agentes.service';
import { ActivatedRoute, Router } from '@angular/router';
import Swal from 'sweetalert2';
import { AuthService } from '../../../auth/services/auth.service';
import { query } from '@angular/animations';

@Component({
  selector: 'app-agregar',
  templateUrl: './agregar.component.html',
  styleUrls: ['./agregar.component.css']
})
export class AgregarComponent implements OnInit{

  id: number = 0;
  tipoBoton: string = 'Agregar';

  agenteForm: FormGroup = this.formBuilder.group({
    nombre: [ '' , [ Validators.required] ],
    detalles:[ '' , [ Validators.required    ] ]
  })

  constructor(
    private formBuilder: FormBuilder,
    private agentesService: AgentesService,
    private activateRoute: ActivatedRoute,
    private router: Router,
    private authService: AuthService
  ){}

  ngOnInit(): void {
    if(this.router.url.includes('editar') ) {
      this.id = this.activateRoute.snapshot.params['id'];
      this.tipoBoton="Actualizar";
      this.llenarFormulario();
    }
    
  }

  getErrorNombre() {
    if (this.agenteForm.controls['nombre'].hasError('required')) {
      return 'Desbes ingresar un nombre';
    }
    return this.agenteForm.controls['nombre'].hasError('email') ? 'Not a valid email' : '';
  }

  getErrorDetalles() {
    if (this.agenteForm.controls['detalles'].hasError('required')) {
      return 'Desbes ingresar un nombre';
    }
    return this.agenteForm.controls['detalles'].hasError('email') ? 'Not a valid email' : '';
  }

  guardar(){
    if (this.agenteForm.invalid) {
      this.agenteForm.markAllAsTouched();
      return;
    }
    if (!this.id) {
      this.agregarAuthPasajero();
    } else {
      this.actualizarAgente()
    }
  }


  private crearAgente(idAgenteUser: number){
    let query = {
      nombre: this.agenteForm.value.nombre,
      detalles: this.agenteForm.value.detalles,
      agenteAuth: {
        id: idAgenteUser
      }
    }
    this.agentesService.addAgente(query).subscribe(
      res => {
        this.irAlListado();
        const Toast = Swal.mixin({
          toast: true,
          position: 'top-end',
          showConfirmButton: false,
          timer: 2000,
          timerProgressBar: true,
          didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer)
            toast.addEventListener('mouseleave', Swal.resumeTimer)
          }
        })
        Toast.fire({
          icon: 'success',
          title: 'Se agrego correctamente'
        })
      }, err =>{

      }
    )
  }

  private actualizarAgente(){
    this.agentesService.updateAgente(this.id,this.agenteForm.value).subscribe(
      res => {
        this.irAlListado();
        const Toast = Swal.mixin({
          toast: true,
          position: 'top-end',
          showConfirmButton: false,
          timer: 2000,
          timerProgressBar: true,
          didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer)
            toast.addEventListener('mouseleave', Swal.resumeTimer)
          }
        })
        Toast.fire({
          icon: 'success',
          title: 'Se actualizo correctamente'
        })
      }, err =>{

      }
    )
  }

  private irAlListado(){
    this.router.navigate(['/agentes/listado']);
  }

  private llenarFormulario(){
    this.agentesService.getAgente(this.id).subscribe(
      res => {
        this.agenteForm.patchValue(res);
      },err => {
      }
    )
  }

  agregarAuthPasajero(){
    let query = {
        usuario: this.agenteForm.value.nombre,
        password: "1234",
        rol: "agente",
    }
    this.authService.addAgenteAuth(query).subscribe(
      res =>{
        this.crearAgente(res.id);  
      }
    )
  }  


}
