import { AfterViewChecked, ChangeDetectorRef, Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { MatStepper } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';
import { DynaDataService, IDirty } from '@xdf/gallery';
import { NavigationService } from '@xdf/layouts';
import { InformationComponent } from './information/information.component';
import { CostosComponent } from './costos/costos.component';
import { EscalaComponent } from './escala/escala.component';
import { VueloService } from '../services/vuelo.service';
import { Vuelo } from '../interfaces/vuelo';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService, NotificationType } from '@xdf/commons';
import { Escala } from '../interfaces/leg';
import { EscalaService } from '../services/escala.service';
import { CostoService } from '../services/costo.service';

@Component({
  selector: 'byte-vuelo',
  templateUrl: './vuelo.component.html',
  styleUrls: ['./vuelo.component.scss']
})
export class VueloComponent implements OnInit, IDirty, AfterViewChecked {

  @ViewChild(InformationComponent, { static: true })
  informationComponent: InformationComponent;
  @ViewChild(EscalaComponent, { static: true })
  escalaComponent: EscalaComponent
  @ViewChild(CostosComponent, { static: true })
  costosComponent: CostosComponent
  // dirty acumulado
  generalDirty = false;
  isLinear = true;
  isNew = true;
  data: any;

  @ViewChild('stepper', { static: true }) stepper: MatStepper;
  processing: boolean;

  constructor(
    private vcRef: ViewContainerRef,
    private activatedRoute: ActivatedRoute,
    private backService: NavigationService,
    private flightService: VueloService,
    private legService: EscalaService,
    private costService: CostoService,
    private router: Router,
    protected dynaDataService: DynaDataService,
    protected translate: TranslateService,
    protected notificationService: NotificationService,
    private readonly changeDetectorRef: ChangeDetectorRef
  ) {
    this.backService.backAnnounced$.subscribe(data => {
      this.router.navigate(['/supervisor/vuelos']);
    });
  }

  ngAfterViewChecked(): void {
    this.changeDetectorRef.detectChanges();
  }

  ngOnInit() {
    this.stepper.selectedIndex = 0;
    this.isNew = this.activatedRoute.snapshot.data.mode === 'create';
    if (this.isNew) {
      this.data = {};
    } else {
      this.data = this.activatedRoute.snapshot.data.record;
    }
    this.informationComponent.buildForm(this.data);
    this.costosComponent.setId(this.data['id']);
    this.escalaComponent.setId(this.data['id']);
  }

  submit() {
    let data = new Vuelo();
    data.airline = this.informationComponent.getForm().controls.airline.value;
    data.airplane = this.informationComponent.getForm().controls.airplane.value;
    data.originAirportId = this.informationComponent.getForm().controls.originAirportId.value;
    data.destinationAirportId = this.informationComponent.getForm().controls.destinationAirportId.value;
    data.departureDate = this.informationComponent.getForm().controls.departureDate.value;
    data.arrivalDate = this.informationComponent.getForm().controls.arrivalDate.value;
    data.departureTime = this.informationComponent.getForm().controls.departureTime.value;
    data.arrivalTime = this.informationComponent.getForm().controls.arrivalTime.value;

    if (this.isNew) {
      this.dynaDataService.create(data).subscribe(res => {
        let legs = this.escalaComponent.getForm();
        let costs = this.costosComponent.getForm();
        legs.map(data => {
          data.flightId = res['id'];
          this.legService.create(data).subscribe();
        });
        costs.map(data => {
          data.flightId = res['id'];
          this.costService.create(data).subscribe();
        });
        this.generalDirty = false;
        this.informationComponent.reset();
        this.costosComponent.reset();
        this.escalaComponent.reset();
        this.router.navigate(['/supervisor/vuelos']);
        const title = this.translate.instant('title.information');
        const message = this.translate.instant('message.create.succesful');
        this.notificationService.showMessage(
          message,
          title,
          NotificationType.success
        );
      }, error => { this.processing = false });
    }
    else {
      this.dynaDataService.update(this.data['id'], data).subscribe(res => {
        let legs = this.escalaComponent.getForm();
        let costs = this.costosComponent.getForm();
        legs.map(data => {
          data.flightId = res['id'];
          this.legService.update(data.id, data).subscribe();
        });
        costs.map(data => {
          data.flightId = res['id'];
          this.costService.update(data.id, data).subscribe();
        });
        const title = this.translate.instant('title.information');
        const message = this.translate.instant('message.update.succesful');
        this.notificationService.showMessage(
          message,
          title,
          NotificationType.success
        );
        this.informationComponent.reset();
        this.costosComponent.reset();
        this.escalaComponent.reset();
        this.router.navigate(['/supervisor/vuelos']);
      });
    }
  }

  isDirty(): boolean {
    let dirty = false;
    dirty = this.informationComponent.isDirty();
    return dirty;
  }

  getRef(): ViewContainerRef {
    return this.vcRef;
  }

  updateDirtyStatus(event: boolean) {
    this.generalDirty = this.generalDirty || event;
  }

  updateValue(event: boolean) {
    if (event) {
      this.submit();
    }
  }
}
