import { Component, OnInit, AfterViewInit, ViewContainerRef, ChangeDetectorRef, ViewChild } from '@angular/core';
import { IFormView, DynaDataService, AuditDialogService, ConfirmationDialogService, RequiredValidator } from '@xdf/gallery';
import { FormGroup, FormBuilder, ValidationErrors, AsyncValidatorFn, FormControl, Validators } from '@angular/forms';
import { ReservationPasajeroGridComponent } from '../reservation-pasajero-grid/reservation-pasajero-grid.component';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService, InitCommonsService, NotificationType } from '@xdf/commons';
import { ReservationVueloGridComponent } from '../reservation-vuelo-grid/reservation-vuelo-grid.component';
import { ReservacionesService } from '../../services/reservaciones.service';

@Component({
  selector: 'byte-reservation-form',
  templateUrl: './reservation-form.component.html',
  styleUrls: ['./reservation-form.component.scss']
})
export class ReservationFormComponent extends IFormView implements OnInit, AfterViewInit {

  aeropuertos: any[] =  [
    {value: 'pendiente', viewValue: 'Pendiente'},
    {value: 'cancelado', viewValue: 'Cancelado'}
  ];
  

  form : FormGroup;
  private taxRatesGrid: ReservationPasajeroGridComponent;
  @ViewChild('taxRatesGrid', { static: false }) set content(
    content: ReservationPasajeroGridComponent
  ) {
    if (content) {
      this.taxRatesGrid = content;
    } else {
      this.taxRatesGrid = undefined;
    }
  }

  private taxRatesGrid2: ReservationVueloGridComponent;
  @ViewChild('taxRatesGrid2', { static: false }) set content2(
    content2: ReservationVueloGridComponent
  ) {
    if (content2) {
      this.taxRatesGrid2 = content2;
    } else {
      this.taxRatesGrid2 = undefined;
    }
  }
  
  constructor(
    protected formBuilder: FormBuilder,
    protected vcRef: ViewContainerRef,
    protected route: ActivatedRoute,
    protected router: Router,
    protected dynaDataService: DynaDataService,
    protected translate: TranslateService,
    protected notificationService: NotificationService,
    protected auditDialogService: AuditDialogService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected init: InitCommonsService,
    private changeDetector: ChangeDetectorRef,
    private reservacionesService: ReservacionesService
    
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);

  }
  ngAfterViewInit(): void {
    if(this.mode !== 'new' && this.record) {
      this.taxRatesGrid2.dataSource.data = this.record.escalas;
      this.getPasajero(this.record.codigoPasajero);
    }
    this.changeDetector.detectChanges();
    this.form.controls['estado'].setValue('pendiente');

  }

  ngOnInit(): void {
    super.ngOnInit();
  }

  protected getFields(): FormGroup {
    let form
    form = this.formBuilder.group({
      diaReservacion: this.createFormControl('diaReservacion', (this.mode !== 'new' && this.record), 
        true, ''),
      estado: this.createFormControl('estado', (this.mode !== 'new' && this.record), true)
    });
    return form;
  }

  private createFormControl(name: string, existRecord?: boolean, required?: boolean, defaultValue?: string,
    validators?: Array<ValidationErrors>, asyncValidators?: Array<AsyncValidatorFn>): FormControl {
   if (!defaultValue) {
     defaultValue = '';
   }
   let validatorList = [];
   if (validators) {
     validatorList = validators;
   }
   if (required) {
     validatorList.push(Validators.required);
   }
   if(name === 'code') return new FormControl({ value: existRecord ? this.record[name] : '', disabled: this.mode !== 'new' }, validatorList, asyncValidators);
   return new FormControl({ value: existRecord ? this.record[name] : '', disabled: this.mode === 'view' }, validatorList, asyncValidators);
  }

  submit() {
    
    if (this.mode == 'new') {
      let result = {
        id: this.mode != 'new' ? this.record.id : 0,
        codigoAgente: 1,
        codigoPasajero: this.taxRatesGrid.dataSource.data[0].id,
        diaReservacion: "2023-02-08T04:51:27.630Z",
        estado: "pendiente",
        costoVuelo: 0
      }
      this.reservacionesService.addItinerario(result).subscribe(
        (res) => {
          this.notificationService.showMessage(
            this.translate.instant('message.create.succesful'),
            this.translate.instant('title.information'),
            NotificationType.success
          );
          this.record = new Object();
          this.form.markAsPristine();
          this.router.navigate([this.returnUrl]);
          this.processing = false;
         for(let i= 0;i < this.taxRatesGrid2.dataSource.data.length; i++){
            this.agregarEscalaAReserva(res['id'],this.taxRatesGrid2.dataSource.data[i].id);
          }
        },
        (error) => {
          this.processing = false;
        }
      );

    } else if (this.mode === 'edit') {

      let result = {
        id: this.record.id,
        codigoAgente: this.record.codigoAgente,
        codigoPasajero: this.record.codigoPasajero,
        estado: this.form.value['estado'],
        diaReservacion: this.record.diaReservacion
      }
      this.dynaDataService.update(this.id, result).subscribe(
        it => {
          const title = this.translate.instant('title.information');
          const message = this.translate.instant('message.update.succesful');
          this.notificationService.showMessage(
            message,
            title,
            NotificationType.success
          );
          this.form.markAsPristine();
          this.router.navigate([this.returnUrl]);
          this.processing = false;
        },
        error => {
          this.processing = false;
        }
      );
    }


  }

  public getEscalasVuelo(id:number){
    this.reservacionesService.getEscalasByVueloId(id).subscribe(
      res => {
        this.taxRatesGrid.dataSource.data = res;

      }
    )
  }

  getPasajero(id:number){
    this.reservacionesService.getPasajero(id).subscribe(
      res => {
        console.log(res);
        let datase = [];
        datase.push(res)
        console.log(datase);
         this.taxRatesGrid.dataSource.data = datase;
      }
    )
  }

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