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

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


  form: FormGroup;
  idPayment: number = 0;

  constructor(
    protected formBuilder: FormBuilder,
    protected vcRef: ViewContainerRef,
    protected activatedRoute: ActivatedRoute,
    protected router: Router,
    protected dynaDataService: DynaDataService,
    protected translate: TranslateService,
    protected notificationService: NotificationService,
    protected auditDialogService: AuditDialogService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected init: InitCommonsService,
    private paymentReservationService: PaymentReservationService
  ) {
    super(vcRef, activatedRoute, 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.addPayment();
  }

  addPayment() {
    let query = {
      paymentAmount: 899,
      status: "pagado"
    };
    this.paymentReservationService.addPayment(query).subscribe(
      res => {
        this.idPayment = res.id;
        this.addPaymentToReservation(res.id);
        console.log(res.id);
      }
    )
  }

  addPaymentToReservation(idPayment: number) {
    let query = {
      id: idPayment
    }
    this.paymentReservationService.addPaymentToReservation(this.id, query).subscribe(
      res => {
        this.updateStatusReservation();
      }
    )
  }

  updateStatusReservation() {
    let query = {
      id: this.record.id,
      codeAgent: this.record.codeAgent,
      codePassenger: this.record.codePassenger,
      status: "pagado",
      dateReservation: this.record.dateReservation
    }
    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]);
      }
    )
  }

}
