import { Component, ViewChild, OnInit } from '@angular/core';

import {HttpClient} from '@angular/common/http';
import { User } from 'src/app/models/user';
import { UserService } from 'src/app/services/user.service';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';


@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit {

  title:string = "Usuarios";
 
  displayedColumns: string[] = ['email', 'first_name', 'last_name', 'role'];
  //displayedColumns: string[] = ['state'];

  listData: User[] = [];
  listUsers:any;
  dataSource = new MatTableDataSource(this.listUsers);

  resultsLength = 0;
  isLoadingResults = true;
  isRateLimitReached = false;

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
  @ViewChild(MatSort, {static: true}) sort: MatSort;
  role_number: any;


  constructor(private userService: UserService) {

    Swal.fire({
      allowOutsideClick: false,
      type: 'info',
      text: 'Espere por favor...'
    });
    Swal.showLoading();
  }

  ngOnInit() {
    this.userService.getAllUsers().subscribe(ans => {
      this.listUsers = ans["data"]["users"];
      this.dataSource.data = this.listUsers;
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    }, (err) => {
      Swal.fire({
        type: 'error',
        title: 'Error en el servidor',
        text: "No su pudo obtener la informaci&oacute;n"
      });
    });

    setTimeout(()=>{
      Swal.close();
    }, 1200);

  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

}
