import { Component, OnInit, ViewChild } from "@angular/core";
import { MatPaginator } from "@angular/material/paginator";
import { MatTableDataSource } from "@angular/material/table";
import { MatDialog } from "@angular/material/dialog";

import { AircraftResp } from "../../models/aircraft";
import { AircraftService } from "../../services/aircraft.service";
import { ServiceComm } from "../../services/service-comm.service";
import { NewAircraftComponent } from "../new-aircraft/new-aircraft.component";
import { AddAction } from "../../models/add-action.enum";

@Component({
  selector: "app-list-of-aircrafts",
  templateUrl: "./list-of-aircrafts.component.html",
  styleUrls: ["./list-of-aircrafts.component.css"]
})
export class ListOfAircraftsComponent implements OnInit {
  public displayedColumns: Array<string> = ["id", "name"];
  public dataSourceTable: MatTableDataSource<AircraftResp>;
  public resultsLength = 0;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  constructor(
    private serviceApi: AircraftService,
    private serviceComm: ServiceComm,
    public dialog: MatDialog
  ) {}

  ngOnInit() {
    this.serviceComm.refreshRequest.subscribe(action => {
      if (action === AddAction.Gear) {
        this.getListOfAircrafts();
      }
    });
    this.serviceComm.UpdatedComponentTitle("List of aircrafts");
    this.getListOfAircrafts();
  }

  private getListOfAircrafts() {
    this.serviceApi.getListOfAircrafts().subscribe(data => {
      setTimeout(() => {
        data.sort((a, b) => (b.name < a.name ? 1 : -1));
        this.dataSourceTable = new MatTableDataSource<AircraftResp>(data);
        this.dataSourceTable.paginator = this.paginator;
        this.resultsLength = data.length;
      }, 2000);
    });
  }

  openDialogToAdd() {
    this.dialog.open(NewAircraftComponent);
  }
}
