import { AfterViewChecked, ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild, ViewContainerRef } from "@angular/core";
import { FormControl, FormGroup, ValidationErrors, Validators } from "@angular/forms";
import { MatDialog, MatTableDataSource } from "@angular/material";
import { ActivatedRoute, Router } from "@angular/router";
import { TranslateService } from "@ngx-translate/core";
import { InitCommonsService, NotificationService, NotificationType } from "@xdf/commons";
import { AuditDialogService, ConfirmationDialogService, DynaDataService, IFormView, ValidatorUtils } from "@xdf/gallery";
import { NavigationService } from "@xdf/layouts";
import { PanelScaleConfigComponent } from "../../components/panel-scale-config/panel-scale-config.component";
import { FlightService } from "../../service/flight.service";
import { AirlineService } from "../../service/airline.service";
import { AircraftService } from "../../service/aircraft.service";
import { AirportService } from "../../../agent/service/airport.service";
import { DatePipe } from "@angular/common";


@Component({
  selector: 'byte-flight-config',
  templateUrl: './flight-config.component.html',
  styleUrls: ['./flight-config.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FlightConfigComponent extends IFormView implements OnInit, AfterViewChecked{

  @ViewChild('scalesComponent', { static: true }) scalesComponent: PanelScaleConfigComponent;

  disabledFields = [
    'id', 'airlineId', 'aircraftId'
  ];
  airports: any[] = [];
  airlines: any[] = [];
  aircrafts: any[] = [];
  scales: any[] = [];
  costs: any[] = [];
  panel: number = 0;

  constructor(
    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 navigationService: NavigationService,
    protected init: InitCommonsService,
    protected validatorUtils: ValidatorUtils,
    private readonly changeDetectorRef: ChangeDetectorRef,
    private activatedRouter: ActivatedRoute,
    public dialog: MatDialog,
    private flightService: FlightService,
    private airlineService: AirlineService,
    private aircraftService: AircraftService,
    private airportService: AirportService
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);
    this.updateContext();
  }
  ngAfterViewChecked(): void {
    this.changeDetectorRef.detectChanges();
  }


  public ngOnInit(): void {
    super.ngOnInit();
    this.icon = '<i class=\"fa fa-plane fa-1_5x\"></i>';
    this.activatedRouter.queryParams.subscribe(params => { this.id = params['id']; });
    this.updateContext();
    this.getAirlines();
    this.getAircrafts();
    this.getAirports();
    this.updateForm(this.id, this.mode);
  }

  public getAirlines() {
    this.airlineService.getAll()
      .subscribe(response => this.airlines = response);
  }

  public getAircrafts() {
    this.aircraftService.getAll()
      .subscribe(response => this.aircrafts = response);
  }

  public getAirports() {
    this.airportService.getAll()
      .subscribe(response => {
        this.airports = response;
      })
  }

  async updateContext() {
    // Obtenemos el id del registro
    await this.activatedRouter.queryParams.subscribe(params => {
      this.id = params['id'];
    });

    // Obtenemos el modo de la vista
    await this.activatedRouter.params.subscribe(params => {
      this.mode = params['mode'];
    });

    this.serviceURL = '/service/flights';
    this.dynaDataService.serviceURL = this.serviceURL;

    if (this.mode !== 'new'){
      await this.flightService.getResult(this.id)
      .subscribe(result => {
        this.record = result;
      })
    }
  }

  updateForm(id, mode) {
    this.mode = mode;
    this.id = id;
    if (this.id) {
      this.dynaDataService.getResult(this.id).subscribe(
        data => {
          this.record = data;
          this.form = this.getFields();
        }
      );
    } else {
      this.record = new Object();
      this.form = this.getFields();
    }
  }

  protected getFields(): FormGroup {
    let form;
    if (this.mode !== 'new' && this.record) {
      form = new FormGroup({
        departureDate: this.createFormControl('departureDate', true, true),
        arrivalDate: this.createFormControl('arrivalDate', true, true),
        airline: this.createFormControl('airlineId', true, true),
        aircraft: this.createFormControl('aircraftId', true, true),
      });
      this.scales = this.record.scales || [];
      this.costs = this.record.costs || [];
    } else {
      form = new FormGroup({
        departureDate: this.createFormControl('departureDate', false, true),
        arrivalDate: this.createFormControl('arrivalDate', false, true),
        airline: this.createFormControl('airlineId', false, true),
        aircraft: this.createFormControl('aircraftId', false, true),
      });

    }
    return form;
  }

  private disabledCondition(controlName?): boolean {
    const disabled = this.mode === 'view' || (this.disabledFields.includes(controlName) && this.mode === 'edit');
    return disabled;
  }

  private createFormControl(name: string, existRecord?: boolean, required?: boolean, defaultValue?: string, validators?: Array<ValidationErrors>): FormControl {
    if (!defaultValue) defaultValue = '';
    let validatorList = [];
    if (validators) validatorList = validators;
    if (required) validatorList.push(Validators.required);
    let valueaux = existRecord ? this.record[name] : '';
    return new FormControl({ value: valueaux, disabled: this.disabledCondition(name) }, validatorList);
  }

  changePanel(panel: number): void {
    this.panel = panel;
  }

  isValidForSave(): boolean {
    return this.form.valid && this.scales.length > 0 && this.costs.length > 0;
  }

  onSubmit() {
    if (this.isValidForSave()) {
      if (this.mode === 'new') {
        const flight = {
          airlineId: this.form.value.airline,
          aircraftId: this.form.value.aircraft,
          departureDate: new DatePipe('en-US').transform(this.form.get('departureDate').value, "yyyy-MM-dd'T'HH:mm:ss"),
          arrivalDate: new DatePipe('en-US').transform(this.form.get('arrivalDate').value, "yyyy-MM-dd'T'HH:mm:ss"),
          scales: this.scales,
          costs: this.costs
        }
        this.flightService.create(flight)
          .subscribe(response => {
            this.notificationService.showMessage("El vuelo se creo satisfactoriamente!", "Vuelo registrado", NotificationType.success);
            this.router.navigate(['/supervisor/flights']);
          });
      } else {
        const flight = {
          departureDate: new DatePipe('en-US').transform(this.form.get('departureDate').value, "yyyy-MM-dd'T'HH:mm:ss"),
          arrivalDate: new DatePipe('en-US').transform(this.form.get('arrivalDate').value, "yyyy-MM-dd'T'HH:mm:ss"),
          costs: this.costs.filter(cost => cost.isNew === true),
        }
        this.flightService.edit(flight, this.id)
          .subscribe(response => {
            this.notificationService.showMessage("El vuelo se actualizo satisfactoriamente!", "Vuelo actualizado", NotificationType.success);
            this.router.navigate(['/supervisor/flights']);
          });
      }
    }
  }

  onAddScale(scale: any) {
    this.scales = [...this.scales, scale];
  }

  onAddCost(cost: any) {
    console.log(cost);
    this.costs = [...this.costs, cost];
  }

}
