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 { AircraftService } from '../../services/aircraft.service';
import { ServiceComm } from '../../services/service-comm.service';
import { AuthenticationService } from '../../services/authentication.service';
import { NewAircraftComponent } from '../new-aircraft/new-aircraft.component';
import { AddAction } from '../../models/add-action.enum';
import { AircraftResp } from '../../models/aircraft';

@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> = ['name', 'imageData'];
  public dataSourceTable: MatTableDataSource<AircraftResp>;
  public resultsLength = 0;
  public isUserAdmin: boolean;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  constructor(private serviceApi: AircraftService,
              private serviceComm: ServiceComm,
              private authenticationService: AuthenticationService,
              public dialog: MatDialog) { 
    this.isUserAdmin = this.authenticationService.currentUserValue.roles === "admin";
  }

  ngOnInit() {
    this.serviceComm.refreshRequest.subscribe(action => {
      if (action === AddAction.Aircraft) {
        this.dialog.closeAll();
        this.getListOfAircrafts();
      }
    });
    this.serviceComm.UpdatedComponentTitle('List of aircrafts');
    this.getListOfAircrafts();
  }

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

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