import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { NGXLogger } from 'ngx-logger';
import { NotificationService } from 'src/app/core/services/notification.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

import { apiUserService } from 'src/app/core/services/api/api.user.service';
import { User } from 'src/app/core/services/model/user.interface';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {

  displayedColumns: string[] = ['username', 'email', 'admin', 'agent'];
  users : MatTableDataSource<User> = new MatTableDataSource<User>();
  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  constructor(
    private logger: NGXLogger,
    private notificationService: NotificationService,
    private titleService: Title,
    private router: Router,
    private apiUserService: apiUserService,
  ) { }

  ngOnInit() {
    this.titleService.setTitle('Jucundus - Users');
    this.logger.log('Users loaded');
    this.refreshUsers()
  }

  refreshUsers(): void {
    this.apiUserService.getAllUsers().subscribe((data: any) => {
      console.log(data);

      this.users = new MatTableDataSource(data);      
      this.users.paginator = this.paginator ?? null;
      this.users.sort = this.sort ?? null;
      
      this.notificationService.openSnackBar("Users loaded");
    });
  }

  openUser(id: string): void {
    this.router.navigate(['/users/edit', id]);
  }
}
