import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild, 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 } from '@xdf/gallery';
import { ReservationsService } from '../../services/reservations.service';
import { ReservationPassengerGridComponent } from '../reservation-passenger-grid/reservation-passenger-grid.component';
import { ReservationFlightGridComponent } from '../reservation-flight-grid/reservation-flight-grid.component';

@Component({
  selector: 'byte-reservation-form',
  templateUrl: './reservation-form.component.html',
  styleUrls: ['./reservation-form.component.scss']
})
export class ReservationFormComponent extends IFormView implements OnInit, AfterViewInit {
  airports: any[] = [
    { value: 'pendiente', viewValue: 'Pendiente' },
    { value: 'cancelado', viewValue: 'Cancelado' }
  ];


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

  private reservationFlightGrid: ReservationFlightGridComponent;
  @ViewChild('reservationFlightGrid', { static: false }) 
  set content2(
    content2: ReservationFlightGridComponent
  ) {
    if (content2) {
      this.reservationFlightGrid= content2;
    } else {
      this.reservationFlightGrid = undefined;
    }
  }

  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 changeDetector: ChangeDetectorRef,
    private reservationsService: ReservationsService

  ) {
    super(vcRef, activatedRoute, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);

  }
  ngAfterViewInit(): void {
    if (this.mode !== 'new' && this.record) {
      this.reservationFlightGrid.dataSource.data = this.record.legs;
      this.getPassenger(this.record.codePassenger);
    }
    this.changeDetector.detectChanges();
    this.form.controls['status'].setValue('pendiente');

  }

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

  protected getFields(): FormGroup {
    let form
    form = this.formBuilder.group({
      dateReservation: this.createFormControl('dateReservation', (this.mode !== 'new' && this.record),
        true, ''),
      status: this.createFormControl('status', (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,
        codeAgent: 1,
        codePassenger: this.reservationPassengerGrid.dataSource.data[0].id,
        dateReservation: "2023-05-04T04:51:27.630Z",
        status: "pendiente",
        flightCost: 0
      }
      this.reservationsService.addItinerary(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.reservationFlightGrid.dataSource.data.length; i++) {
            this.addLegToReservation(res['id'], this.reservationFlightGrid.dataSource.data[i].id);
          }
        },
        (error) => {
          this.processing = false;
        }
      );

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

      let result = {
        id: this.record.id,
        codeAgent: this.record.codeAgent,
        codePassanger: this.record.codePassenger,
        status: this.form.value['status'],
        dateResrevation: this.record.dateReservation
      }
      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 getLegsFlight(id: number) {
    this.reservationsService.getLegsByFlightId(id).subscribe(
      res => {
        this.reservationPassengerGrid.dataSource.data = res;

      }
    )
  }

  getPassenger(id: number) {
    this.reservationsService.getPassenger(id).subscribe(
      res => {
        console.log(res);
        let datase = [];
        datase.push(res)
        console.log(datase);
        this.reservationPassengerGrid.dataSource.data = datase;
      }
    )
  }

  addLegToReservation(idReservation: number, id: number) {
    this.reservationsService.addLegToReservation(idReservation, id).subscribe(
      res => {
        console.log(res);
      }
    )
  }
}
