import { Component, HostListener, Input, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { PageEvent } from '@angular/material/paginator';
import { Sort } from '@angular/material/sort';
import { AuthService } from 'src/app/services/auth.service';
import { UserManagementService } from 'src/app/services/user.management.service';

@Component({
  standalone: false,
  selector: 'ui-users',
  templateUrl: './users.page.html',
  styleUrls: ['./users.page.scss']
})
export class PageUsers implements OnInit {

  @Input() users: any;
  pageSizeOptions: number[] = [1, 2, 3, 4, 5, 10, 15, 30, 50, 100];
  sort: string = "username";
  descending: boolean = false;
  filterOpen: boolean = true;

  columns: string[] = [];

  username: string = "";

  constructor(
    private userManagementService: UserManagementService,
    private authService: AuthService,
    private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.users = {};
    this.update();
    this.applyResize(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);

    this.authService.auth.subscribe({
      next: (auth) => {
        this.username = auth.username;
      },
      error: (error) => {
        this.username = ""
      }
    })
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.applyResize(event.target.innerWidth || event.target.documentElement.clientWidth || event.target.body.clientWidth)
  }

  applyResize(width: number) {
    if (width < 992) {
      this.columns = ['username', 'name', 'email']
    } else {
      this.columns = ['username', 'name', 'email', 'about'];
    }
  }

  update() {
    const filter = this.users.filter || "";
    this.userManagementService.fetch(this.users.limit || 15, this.users.offset || 0, this.sort, this.descending, filter).subscribe({
      next: (data: any) => {
        this.users = data;
        this.users.filter = filter;
      }, error: (error) => {
        this.users = { error: error };
      }
    })
  }

  applyPage(event: PageEvent) {
    this.users.limit = event.pageSize;
    this.users.offset = event.pageSize * event.pageIndex;
    this.update();
  }

  applySort(event: Sort) {
    this.sort = event.direction ? event.active : 'username';
    this.descending = event.direction !== 'asc';
    this.update();
  }

  setFilter(target: EventTarget) {
    const value = (target as HTMLInputElement).value;
    if (value != this.users.filter) {
      this.users.filter = value;
      this.users.offset = 0;
      this.update();
    }
  }

}
