import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatStepper } from '@angular/material';
import { ActivatedRoute } from '@angular/router';
import { ColumnTemplate } from '@xdf/gallery';
import { AirportService } from '../../service/airport.service';
import { FlightSearchService } from '../../../supervisor/service/flight-search.service';
import { DatePipe } from '@angular/common';
import { ReservationService } from '../../service/reservation.service';

const columnTemplateArray = [
  {
    name: 'id',
    sortable: false,
    title: 'flight_id',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'number',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'airline',
    sortable: true,
    title: 'flight_airline',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'aircraft',
    sortable: true,
    title: 'flight_aircraft',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'flightType',
    sortable: true,
    title: 'flight_travelClass',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'departureDate',
    sortable: true,
    title: 'flight_departureDate',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'arrivalDate',
    sortable: true,
    title: 'flight_arrivalDate',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'amount',
    sortable: true,
    title: 'flight_price',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  }
];

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

  airports: any[] = [];

  columnTemplateArray: ColumnTemplate[];
  dataSource: any[] = [];
  displayedColumns = new Array<string>();
  filterTags = [];
  sortDirection: string = 'asc';
  flightSelected: number;

  @Input()
  public airportOrigin: number;

  @Input()
  public airportDestination: number;

  @Input()
  public departureDate: string;

  public id: number;

  public flightSelectionFormGroup = new FormGroup({});

  constructor(private formBuilder: FormBuilder,
    private activatedRoute: ActivatedRoute,
    private reservationService: ReservationService,
    private airportService: AirportService,
    private activateRoute: ActivatedRoute,
    private flightSearchService: FlightSearchService) { }

  @Input()
  searchResults: any[] = [];

  @Input()
  public stepper: MatStepper;

  @Output()
  public onFlightSelected: EventEmitter<number> = new EventEmitter();

  public mode: string;

  ngOnInit() {
    this.columnTemplateArray = columnTemplateArray;

    this.columnTemplateArray.forEach(column => {
      this.displayedColumns.push(column.name);
    });

    this.airportService.getAll()
      .subscribe(data => this.airports = data);

    this.activateRoute.params.subscribe(params => this.mode = params.mode);

    this.displayedColumns.push("actions");
    this.buildForm();
    this.updateData();
  }

  searchFLight(data: any) {
    this.flightSearchService.searchFlights(data.airportOrigin, data.airportDestination, data.travelDate)
      .subscribe(result => {
        this.searchResults = result;
        this.dataSource = [...result];
      });
  }



  getDisabledCondicion() {
    return this.mode !== 'new';
  }

  buildForm(): void {
    this.flightSelectionFormGroup = new FormGroup({
      origin: new FormControl({ value: '', disabled: this.getDisabledCondicion()}, [Validators.required]),
      destination: new FormControl({ value: '', disabled: this.getDisabledCondicion()}, [Validators.required]),
      departureDate: new FormControl({ value: '', disabled: this.getDisabledCondicion()}, [Validators.required])
    });
  }

  updateData() {
    if (this.mode !== 'new') {
      this.activateRoute.queryParams.subscribe(params => {
        this.id = params['id'];
      });
      this.reservationService.getById(this.id)
        .subscribe(reservation => {
          this.flightSelectionFormGroup.get('origin').setValue(reservation.airportOriginId);
          this.flightSelectionFormGroup.get('destination').setValue(reservation.airportDestinationId);
          this.flightSelectionFormGroup.get('departureDate').setValue(reservation.departureDate);
          this.flightSelected = reservation.flightId;
          this.dataSource = [...reservation.flightSearchBean];
        });
    }
  }

  onSearch() {
    if (this.flightSelectionFormGroup.valid) {
      const searchFlight = {
        airportOrigin: this.flightSelectionFormGroup.get('origin').value,
        airportDestination: this.flightSelectionFormGroup.get('destination').value,
        travelDate: new DatePipe('en-US').transform(this.flightSelectionFormGroup.get('departureDate').value, "yyyy-MM-dd'T'HH:mm:ss")
      }
      this.searchFLight(searchFlight);
    }
  }

  onSelect(item: any) {
    this.flightSelected = item.id;
    this.onFlightSelected.emit(item);
  }

  onNext() {
    if (this.flightSelected) {
      this.stepper.next();
    }
  }
}
