import { Component, ViewChild, OnInit } from '@angular/core';
import { Organization } from "@app/models/organization";
import { OrganizationsService } from "@app/services/organizations.service";
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import Swal from 'sweetalert2';
import { Router } from '@angular/router';
import { AuthService } from '@app/services/auth2.service';

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

  title:string = "Organizaciones";  
 
  displayedColumns: string[] = ['name','contactName', 'contactNumber', 'country', 'id'];
  //displayedColumns: string[] = ['state'];

  listData: Organization[] = [];
  listOrganization:any;
  dataSource = new MatTableDataSource(this.listData);
  resultsLength = 0;
  isLoadingResults = true;
  isRateLimitReached = false;

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


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

  ngOnInit() {

    this.orgService.getListOrganizations().subscribe(res =>
      this.listData = res
    );
    
    this.orgService.getAllOrganizations().subscribe(ans => {
      this.listOrganization = ans["data"]["organizations"];
      this.dataSource.data = this.listOrganization;
      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 informacion"
      });
    });
    
    //this.chartjs = true;
    setTimeout(()=>{
      Swal.close();
    }, 1200);

  }

  delete_organization(id: string){
    Swal.fire({
      allowOutsideClick: false,
      type: 'warning',
      title: '¿Esta seguro?',
      text: 'No podrá revertir esta acción',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Borrar registro',
    })
    .then((result) => {
        if (result.value) {
          this.delete_organization2(id);
        }
    });
  }

  delete_organization2(id: string){
    this.orgService.deleteOrganization(id)
    .subscribe(
      data => {
        if (data["success"] == true) {
          //document.getElementById(id).remove();
          Swal.fire({
            allowOutsideClick: false,
            type: 'success',
            text: 'Registro eliminado con exito'
          }).then((result) => {
            if (result.value) {
              this.reloadComponent();
            }
          });
          //window.location.href="#/organizations";
        }
        else {
          Swal.fire({
            allowOutsideClick: false,
            type: 'error',
            text: "No tienes permiso para eliminar el registro"
          });
        }  
      },
      err => {
        Swal.fire({
          type: 'error',
          title: 'Error en el servidor',
          text: err.message
        });
      });
  }


  reloadComponent(){
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
    this.router.onSameUrlNavigation = 'reload';
    this.router.navigate(['/organizations']);
  }

  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
  }

}