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 { Observable } from 'rxjs';
import { JumpResp } from '../../models/jump';
import { JumpService } from '../../services/jump.service';
import { ServiceComm } from '../../services/service-comm.service';
import { JumpInfosComponent } from "../jump-infos/jump-infos.component";

@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> = [
    'infos',
    'id',
    'jumpDate',
    'jumpType',
    'aircraft',
    'dropZone'
  ];
  public dataSourceTable;
  public resultsLength = 0;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

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

  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;
      }, 500);
    });
  }

  openDialog(item: JumpResp) {
    this.dialog.open(JumpInfosComponent, {
      data: item //,
      // position: {
      //   top: '0px',
      //   left: '0px'
      // }
    });
  }
}
