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 { IFormView, DynaDataService, AuditDialogService, ConfirmationDialogService, RequiredValidator } from '@xdf/gallery';
import { InitCommonsService, NotificationService, NotificationType } from '@xdf/commons';
import { FlightService } from '../../services/flight.service';
import { FlightLegsGridComponent } from '../flight-legs-grid/flight-legs-grid.component';

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

  airports: any[] = [];
  
  form: FormGroup;

  private taxRatesGrid: FlightLegsGridComponent;
  
  @ViewChild('taxRatesGrid', {static: false}) 
  set content (
    content: FlightLegsGridComponent
  ) {
    if (content) {
      this.taxRatesGrid = content;
    } else {
      this.taxRatesGrid = 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,
    protected changeDetector: ChangeDetectorRef,
    private flightService: FlightService ) {
      super(vcRef, activatedRoute, router, dynaDataService,
            translate, notificationService, auditDialogService,
            confirmationDialogService, init);
          }

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

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

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

  addLegsToFlight(idFlight: number) {
    for(let i = 0; i < this.taxRatesGrid.dataSource.data.length; i++) {
      this.taxRatesGrid.dataSource.data[i].flightCode = idFlight;

      this.flightService.addLeg(this.taxRatesGrid.dataSource.data[i])
      .subscribe(res => {})
    }
  }

  protected getFields(): FormGroup {
    let form;
    form = this.formBuilder.group({

      airlineCode: this.createFormControl('airlineCode', (this.mode !== 'new' && this.record),
      true, '', [RequiredValidator.isRequired]),

      codeTypeAircraft: this.createFormControl('codeTypeAircraft', (this.mode !== 'new' && this.record), true),

      codeAirportOrigin: this.createFormControl('codeAirportOrigin', (this.mode !== 'new' && this.record),
      true, '', [RequiredValidator.isRequired]),

      codeAirportDestination: this.createFormControl('codeAirportDestination', (this.mode !== 'new' && this.record),
      true, '', [RequiredValidator.isRequired]),

      flightCost: this.createFormControl('flightCost', (this.mode !== 'new' && this.record), true, '', [RequiredValidator.isRequired]),

      departureDate: this.createFormControl('departureDate', (this.mode !== 'new' && this.record),
      true, '', [RequiredValidator.isRequired]),

      arrivalDate: this.createFormControl('arrivalDate', (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,
        airlineCode: this.form.value['airlineCode'],
        codeTypeAircraft: this.form.value['codeTypeAircraft'],
        codeAirportOrigin: this.form.value['codeAirportOrigin'],
        codeAirportDestination: this.form.value['codeAirportDestination'],
        flightCost: this.form.value['flightCost'],
        departureDate: this.form.value['departureDate'],
        arrivalDate: this.form.value['arrivalDate']
      }

      if(this.mode == 'new') {
        this.dynaDataService.create(result).subscribe(
          (res) => {
            this.addLegsToFlight(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;
          }
        );
      }
    }
}
