import { Component, ElementRef, ViewChild, OnInit } from '@angular/core';
import { Pasajero } from '../../../pasajeros/interfaces/pasajeros.inteface';
import { PageEvent } from '@angular/material/paginator';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import Swal from 'sweetalert2';
import { Router } from '@angular/router';
import { formatDate } from '@angular/common';
import { PasajerosService } from '../../../pasajeros/services/pasajeros.service';
import { VuelosService } from '../../../vuelos/services/vuelos.service';
import { EscalasService } from '../../../vuelos/services/escalas.service';
import { ReservasService } from '../../services/reservas.service';
declare let Email: any;

@Component({
  selector: 'app-agregar',
  templateUrl: './agregar.component.html',
  styleUrls: ['./agregar.component.css']
})
export class AgregarComponent implements OnInit{
  
  @ViewChild('closeModal') modalVer: ElementRef | undefined;
  @ViewChild('closeModalVuelo') modalVerVuelo: ElementRef | undefined;

  pasajeroID:number = 0;
  estado:string = "pendiente";
  reservaId: number = 0;
  cantidadEscalas= 0;
  correoPasajero: string = "";
  pasajerosModal: Pasajero[] = [];
  pasajero: Pasajero | undefined;
  vuelosModal: any[] = [];
  escalasVuelo: any[] = [];

  page_size: number = 5;
  page_number: number = 1;
  pageSizeOptions = [5,10,20,50];

  page_sizeV: number = 5;
  page_numberV: number = 1;
  pageSizeOptionsV = [5,10,20,50];

  reservaForm: FormGroup = this.formBuilder.group({
    diaReservacion: [ '' ],
    estado: [ ''],
    idPasajero: [ '' , [ Validators.required] ]
  })

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private pasajerosService: PasajerosService,
    private vuelosService: VuelosService,
    private escalasService: EscalasService,
    private reservasService: ReservasService
  ){}  

  ngOnInit(): void {
    this.reservaForm.controls['estado'].setValue('Pendiente');
    let currentDate = new Date();
    const cValue = formatDate(currentDate, 'yyyy-MM-dd', 'en-US');
    this.reservaForm.controls['diaReservacion'].setValue(cValue);
    this.listarPasajeros();
    this.listarVuelos(); 
  }

  handlePage(e: PageEvent){
    this.page_size = e.pageSize;
    this.page_number = e.pageIndex +1;
  }
  handlePage2(e2: PageEvent){
    this.page_sizeV = e2.pageSize;
    this.page_numberV = e2.pageIndex +1;
  }

  agregarPasajero(id:number){
    this.modalVer?.nativeElement.click();
    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)
      }
    })
    this.reservaForm.controls['idPasajero'].setValue(id);
    this.pasajeroID = id;
    this.getPasajero(id);
    Toast.fire({
      icon: 'success',
      title: 'Se Agrego correctamente'
    })
  }

  listarPasajeros(){
    this.pasajerosService.getPasajeros().subscribe(
      res => {
        this.pasajerosModal = res;
      }
    )
  }

  getPasajero(id: number){
    this.pasajerosService.getPasajero(id).subscribe(
      res => {
        this.correoPasajero= res.correo;
        this.pasajero = res;
      }
    )
  }

  listarVuelos(){
    this.vuelosService.getVuelos().subscribe(
      res => {
        this.vuelosModal = res;
      }
    )
  }

  agregarVuelo(id:number){
    this.modalVerVuelo?.nativeElement.click();
    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)
      }
    })
    this.listarEscalasByVuelo(id);
    Toast.fire({
      icon: 'success',
      title: 'Se Agrego correctamente'
    })
  }

  listarEscalasByVuelo(id: number){
    this.escalasService.getEscalasByVueloId(id).subscribe(
      res => {
        this.reservaId = id;
        this.cantidadEscalas = res.length;
        this.escalasVuelo = res;
        console.log(this.escalasVuelo);
      }
    )
  }

  agregarReserva(){
    if (this.reservaForm.invalid || this.reservaId == 0) {
      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: 'error',
        title: 'Tienes un error'
      })
      return;
    }

    let reserva: any = {
      "estado": this.estado,
      "pasajero" : {
          "id" : this.pasajeroID
      },
      "agente" : {
          "id" : localStorage.getItem('id')
      }
    }
    this.reservasService.addReserva(reserva).subscribe(
      (res) => {
      this.mandarCorreo();
      for(let i= 0;i < this.escalasVuelo.length; i++){
          this.agregarEscalaAReserva(res['id'],this.escalasVuelo[i].id);
        }
      }
    )

    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 la reserva'
    })
    this.irAlListado();
  }

  agregarEscalaAReserva(idReserva: number,id:number){
    this.escalasService.addEscalaAReserva(idReserva,id).subscribe(
      res => {
        console.log(res);
      }
    )
  }

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

  mandarCorreo(){
    Email.send({
      Host : 'smtp.elasticemail.com',
      Username : 'charles.torres@urp.edu.pe',
      Password : 'CBD3EC898F0998B92BB1520FD6120CF6B437',
      To : this.correoPasajero,
      From : 'charles.torres@urp.edu.pe',
      Subject : 'Pago Reserva',
      Body : `<h1>Tienes una Reserva pendiente de pago:</h1><br><h2>Creedenciales de Inicio de Sesion:</h2></br><strong>Email:</strong>
      ${this.correoPasajero}<br><strong>Codigo:</strong>1234<br>Ingresa a nuestra pagina:http://localhost:4200/auth/login-pasajero`
    }); 
  }
}

