import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import {AbstractControl, AsyncValidatorFn, FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {ActivatedRoute,Router} from '@angular/router';
import {TranslateService} from '@ngx-translate/core';
import {NotificationService,InitCommonsService, NotificationType} from '@xdf/commons';
import {AuditDialogService, ConfirmationDialogService, DynaDataService, IFormView, RequiredValidator} from '@xdf/gallery';
import {Observable,of} from 'rxjs';
import {map} from 'rxjs/operators';
import { VueloEscalasGridComponent } from '../vuelo-escalas-grid/vuelo-escalas-grid.component';
import { VuelosService } from '../../services/vuelo.service';

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


  aeropuertos: any[] = [];

  form : FormGroup;
  private taxRatesGrid: VueloEscalasGridComponent;
  @ViewChild('taxRatesGrid', { static: false }) set content(
    content: VueloEscalasGridComponent
  ) {
    if (content) {
      this.taxRatesGrid = content;
    } else {
      this.taxRatesGrid = 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 aeropuertoService: VuelosService,
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);

  }
  ngAfterViewInit(): void {
    if(this.mode !== 'new' && this.record) {
      this.taxRatesGrid.dataSource.data = this.taxRatesGrid.autoSort(this.record.escalas);
    }
    this.changeDetector.detectChanges();
  }

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

  protected getFields(): FormGroup {
    let form
    form = this.formBuilder.group({
      codigoAerolinea: this.createFormControl('codigoAerolinea', (this.mode !== 'new' && this.record), 
        true, '', [RequiredValidator.isRequired]),
      codigoTipoAeronave: this.createFormControl('codigoTipoAeronave', (this.mode !== 'new' && this.record), true),
      codigoAeropuertoOrigen: this.createFormControl('codigoAeropuertoOrigen', (this.mode !== 'new' && this.record), 
      true, '', [RequiredValidator.isRequired]),
      codigoAeropuertoDestino: this.createFormControl('codigoAeropuertoDestino', (this.mode !== 'new' && this.record), 
      true, '', [RequiredValidator.isRequired]),
      costo: this.createFormControl('costo', (this.mode !== 'new' && this.record), 
      true, '', [RequiredValidator.isRequired]),
      fechaSalida: this.createFormControl('fechaSalida', (this.mode !== 'new' && this.record), 
      true, '', [RequiredValidator.isRequired]),
      fechaLlegada: this.createFormControl('fechaLlegada', (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() {

    this.processing = true;
    let result = {
      id: this.mode != 'new' ? this.record.id : 0,
      codigoAerolinea: this.form.value['codigoAerolinea'],
      codigoTipoAeronave: this.form.value['codigoTipoAeronave'],
      codigoAeropuertoOrigen: this.form.value['codigoAeropuertoOrigen'],
      codigoAeropuertoDestino: this.form.value['codigoAeropuertoDestino'],
      costo: this.form.value['costo'],
      fechaSalida: this.form.value['fechaSalida'],
      fechaLlegada: this.form.value['fechaLlegada']
    }

    if (this.mode == 'new') {
      this.dynaDataService.create(result).subscribe(
        (res) => {
          this.agregarEscalasAlVuelo(res['id']);
          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;
        },
        (error) => {
          this.processing = false;
        }
      );

    }
  }

  listarAeropuertos(){
    this.aeropuertoService.getAeropuertos().subscribe(
      res => {
        this.aeropuertos = res;
        console.log(res);
      }
    )
  }

  agregarEscalasAlVuelo(idVuelo: number){

    for(let i = 0; i < this.taxRatesGrid.dataSource.data.length; i++){
      this.taxRatesGrid.dataSource.data[i].codigoVuelo = idVuelo;
      
      console.log(this.taxRatesGrid.dataSource.data[i]);
      this.aeropuertoService.addEscala(this.taxRatesGrid.dataSource.data[i]).subscribe(
        res =>{
        }
      ) 
      }
  }

}

 


