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 { AddAction } from '../../models/add-action.enum';
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',
    'actions'
  ];
  public dataSourceTable;
  public resultsLength = 0;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

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

  ngOnInit() {
    this.serviceComm.refreshRequest.subscribe(action => {
      if (action === AddAction.Jump) {
        this.dialog.closeAll();
        this.getListOfJumps();
      }
    });
    this.serviceComm.UpdatedComponentTitle('List of jumps');
    this.getListOfJumps();
  }

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

  openDialog(item: JumpResp, editMode: boolean) {
    this.dialog.open(JumpInfosComponent, 
                     { data: { "jump": item, "editMode": editMode},
                       maxHeight: "400px",
                       minWidth: "350px"
                     });
  }

  toShow(item: JumpResp) {
    return item.withCutaway === true || item.notes != undefined;
  }

  delete(item: JumpResp) {
    let data : Array<JumpResp> = this.dataSourceTable.data;
    data = data.filter(d => d.id !== item.id);
    
    this.dataSourceTable.data = data;
    this.resultsLength = data.length;

    this.serviceApi.DeleteJump(item);
  }
}
