import { Component, OnInit, ViewContainerRef, ChangeDetectorRef, AfterViewInit } from '@angular/core';
import { FormBuilder, FormGroup, ValidationErrors, AsyncValidatorFn, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { DynaDataService, AuditDialogService, ConfirmationDialogService, IFormView, RequiredValidator } from '@xdf/gallery';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService, InitCommonsService, NotificationType } from '@xdf/commons';
import { PagoReservaService } from '../../services/pago-reserva.service';

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

  form : FormGroup;
  idPago: number = 0;

  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 pagoReservaService: PagoReservaService
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);

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

  ngAfterViewInit(): void { }

  protected getFields(): FormGroup {
    let form
    form = this.formBuilder.group({
      tarjeta: this.createFormControl('tarjeta', (this.mode !== 'new' && this.record), 
        true, '', [RequiredValidator.isRequired]),
      nombre: this.createFormControl('nombre', (this.mode !== 'new' && this.record), 
        true, '', [RequiredValidator.isRequired]),
      cvv: this.createFormControl('cvv', (this.mode !== 'new' && this.record), 
        true, '', [RequiredValidator.isRequired]),
      fecha: this.createFormControl('fecha', (this.mode !== 'new' && this.record), 
        true, '', [RequiredValidator.isRequired])
    });
    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(): void {
      this.agregarPago();
  }

  agregarPago(){
    let query = {
      pago: 800,
      estado: "pagado"
    }
    this.pagoReservaService.addPago(query).subscribe(
      res =>{
        this.idPago = res.id;
       this.agregarPagoAReserva(res.id);
       console.log(res.id);
      }
    )
  }

  agregarPagoAReserva(idPago: number){
    let query = {
      id: idPago
    }
    this.pagoReservaService.addPagoAReserva(this.id,query).subscribe(
      res => {
        this.actualizarEstadoReserva();
      }
    )
  }

  actualizarEstadoReserva(){   
    let query = {
      id: this.record.id,
      codigoAgente: this.record.codigoAgente,
      codigoPasajero: this.record.codigoPasajero,
      estado: "aprobado",
      diaReservacion: this.record.diaReservacion
    }
    this.dynaDataService.update(this.id, query).subscribe(
      res => {
        this.notificationService.showMessage(
          this.translate.instant('message.create.succesful'),
          this.translate.instant('title.information'),
          NotificationType.success
        );
        this.form.markAsPristine();
        this.router.navigate([this.returnUrl]);
      }
    )
  }
}
