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

import { Observable } from 'rxjs';
import { JumpResp } from '../../models/jump';
import { JumpService } from '../../services/jump.service';
import { ServiceComm } from '../../services/service-comm.service';

@Component({
  selector: 'app-list-of-jumps',
  templateUrl: './list-of-jumps.component.html',
  styleUrls: ['./list-of-jumps.component.css']
})
export class ListOfJumpsComponent implements OnInit {
  public listOfJumps: Observable<Array<JumpResp>>;
  public displayedColumns: Array<string> = [
    'id',
    'jumpDate',
    'jumpType',
    'aircraft',
    'dropZone',
    'gear'
  ];
  public dataSourceTable;
  public resultsLength = 0;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  constructor(
    private serviceApi: JumpService,
    private serviceComm: ServiceComm
  ) { }

  ngOnInit() {
    this.serviceComm.UpdatedComponentTitle('List of jumps');
    this.getListOfJumps();
  }

  getListOfJumps() {
    this.listOfJumps = this.serviceApi.getListOfJumps();
    this.listOfJumps.subscribe(data => {
      setTimeout(() => {
        data.sort((a, b) => b.jumpDate.getTime() - a.jumpDate.getTime());
        this.dataSourceTable = new MatTableDataSource<JumpResp>(data);
        this.dataSourceTable.paginator = this.paginator;
        this.resultsLength = data.length;
      }, 2000);
    });
  }
}
