import { Component, HostListener, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { FlightService } from '../../services/flight.service';

@Component({
  selector: 'byte-flight-leg-dialog',
  templateUrl: './flight-leg-dialog.component.html',
  styleUrls: ['./flight-leg-dialog.component.scss']
})
export class FlightLegDialogComponent implements OnInit {

  form: FormGroup;
  logoSrc: any;
  minDate: Date;
  record: any;
  mode: any;
  title = "dialog_rate_new_title"
  airports: any[] = [];



  constructor(
    public dialogRef: MatDialogRef<FlightLegDialogComponent>,
    private formBuilder: FormBuilder,
    private flightService: FlightService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.record = data.record;
    this.mode = data.mode;
    this.minDate = data.minDate;

  }

  ngOnInit() {
    this.listAirports();
    this.logoSrc = "assets/images/logo_byte_menu-min.png";
    this.form = this.formBuilder.group({
      arrivalDate: new FormControl({ disabled: this.mode === 'view' }, [Validators.required]),
      departureDate: new FormControl({ disabled: this.mode === 'view' }, [Validators.required]),
      codeAirportOrigin: new FormControl([Validators.required]),
      codeAirportDestination: new FormControl([Validators.required]),
      codeFlight: new FormControl([Validators.required])
    });
    console.log(this.record);
    if (this.record) {
      this.form.controls['arrivalDate'].setValue(this.record.arrivalDate);
      this.form.controls['codeAirportOrigin'].setValue(this.record.codeAirportOrigin);
      this.form.controls['codeAirportDestination'].setValue(this.record.codeAirportDestination);
      this.form.controls['departureDate'].setValue(this.record.departureDate);
    } else {
      this.form.controls['codeAirportOrigin'].setValue('');
      this.form.controls['codigoAirportDestination'].setValue('');

    }
  }

  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close(null);
  }
  close() {
    this.dialogRef.close(null);
  }
  save() {
    this.dialogRef.close(this.form.value)
  }

  listAirports() {
    this.flightService.getAirports().subscribe(
      res => {
        this.airports = res;
        console.log(res);
      }
    )
  }

}
