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

import { Plant } from 'src/app/models/plant';
import { PlantsService } from 'src/app/services/plants.service';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';

import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
import { UserService } from '@app/services/user.service';
import { AuthService } from '@app/services/auth2.service';

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

  title:string = "Plantas";
 
  displayedColumns: string[] = ['name', 'country', 'city', 'id'];
  //displayedColumns: string[] = ['state'];

  listData: Plant[] = [];
  listPlant:any;
  dataSource = new MatTableDataSource(this.listPlant);

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

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


  constructor(private orgService: PlantsService, private authService: AuthService) {
    Swal.fire({
      allowOutsideClick: false,
      type: 'info',
      text: 'Espere por favor...'
    });
    Swal.showLoading();
  }

  ngOnInit() {
    this.orgService.getAllAssets().subscribe(ans => {
      this.listPlant = ans["data"]["assets"];
      this.dataSource.data = this.listPlant;
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });

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

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

  allowedUser(){
    let is_allowed: boolean;
    if(+this.authService.getUserLevel() < 3){
      is_allowed = false;
    }
    else {
      is_allowed = true;
    }
    console.log(is_allowed);
    return is_allowed
  }

}
