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 { AddAction } from "../../models/add-action.enum";
import { JumpTypeResp } from "../../models/jumpType";
import { JumpTypeService } from "../../services/jump-type.service";
import { ServiceComm } from "../../services/service-comm.service";
import { AuthenticationService } from '../../services/authentication.service';
import { NewJumpTypeComponent } from "../new-jump-type/new-jump-type.component";

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

  constructor(private serviceApi: JumpTypeService,
              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.JumpType) {
        this.dialog.closeAll();
        this.getListOfJumpTypes();
      }
    });
    this.serviceComm.UpdatedComponentTitle("List of jump types");
    this.getListOfJumpTypes();
  }

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

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