import { MdbTablePaginationComponent, MdbTableDirective } from 'angular-bootstrap-md';

import { Component, OnInit, ViewChild, HostListener, AfterViewInit, ChangeDetectorRef } from '@angular/core';
import { AuthGuard } from '../services/auth.guard';
import { UsersService } from '../services/users.service';

@Component({
  selector: 'table-users',
  templateUrl: './table-users.component.html',
  styleUrls: ['./table-users.component.scss']
})
export class TableUsersComponent implements OnInit, AfterViewInit {
  
  @ViewChild(MdbTablePaginationComponent, { static: true }) mdbTablePagination: MdbTablePaginationComponent;
  @ViewChild(MdbTableDirective, { static: true }) mdbTable: MdbTableDirective;
  
  previous: any = [];
  searchText: string = '';
  maxVisibleItems: number = 25;
  totalCount: number = 0;

  currentUser;
  loading: boolean = false;
  elements = [];

  @HostListener('input') oninput() {
    this.mdbTablePagination.searchText = this.searchText;
  }

  constructor(private cdRef: ChangeDetectorRef, private _usersService: UsersService, private _auth: AuthGuard) { 
    this._auth.getUserInfo().subscribe( value => {
        this.currentUser = value;
      });  
  }

  private _initElements(): void {
    this.mdbTable.setDataSource(this.elements);
    this.elements = this.mdbTable.getDataSource();
    this.previous = this.mdbTable.getDataSource();
  }

  ngOnInit() {
    this.refreshData();
  }

  refreshData() {
    this.loading = true;
    this.searchText = "";
    var usersSub = this._usersService.getUsers().subscribe( res => {
      usersSub.unsubscribe();
      res.results.forEach(u=>{
        u.lastLogin = u.lastLogin || u.created;
      });
      this.elements = res.results; 
      this.totalCount = res.total;
      this.loading = false;
      this._initElements();
    });
  }

  ngAfterViewInit() {
    
    this.mdbTablePagination.setMaxVisibleItemsNumberTo(this.maxVisibleItems);

    this.mdbTablePagination.calculateFirstItemIndex();
    this.mdbTablePagination.calculateLastItemIndex();
    this.cdRef.detectChanges();
  }

  searchItems() {
    const prev = this.mdbTable.getDataSource();

    if (!this.searchText) {
      this.mdbTable.setDataSource(this.previous);
      this.elements = this.mdbTable.getDataSource();
    }

    if (this.searchText) {
      this.elements = this.mdbTable.searchLocalDataBy(this.searchText);
      this.mdbTable.setDataSource(prev);
    }

    this.mdbTablePagination.calculateFirstItemIndex();
    this.mdbTablePagination.calculateLastItemIndex();

    this.mdbTable.searchDataObservable(this.searchText).subscribe(() => {
      this.mdbTablePagination.calculateFirstItemIndex();
      this.mdbTablePagination.calculateLastItemIndex();
    });
  }

  FieldsChange(user: any, value:any) {
    var patchData = {"role": value.checked? "admin": "user"};
    this._usersService.updateUser(user._id, patchData).subscribe( res1 => {
      user.role = res1.role;
    });
  }

  onImgError(event, user){
    event.target.src = 'https://ui-avatars.com/api/?name='+user.displayName+'&background=random&size=40'
  }

}