import { Component, Input, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { PageEvent } from '@angular/material/paginator';
import { Sort } from '@angular/material/sort';
import { debounceTime, Observable, switchMap } from 'rxjs';
import { TurnoverManagementService } from 'src/app/services/turnover.management.service';
import { UserManagementService } from 'src/app/services/user.management.service';

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

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

  columns: string[] = ['username', 'price', 'timeInvestment'];


  users: Observable<any>;
  usersFormControl = new FormControl();

  constructor(
    private turnoverManagementService: TurnoverManagementService,
    private userManagementService: UserManagementService
  ) { }

  ngOnInit(): void {
    this.entries = {};
    this.update();
    this.users = this.usersFormControl
      .valueChanges
      .pipe(
        debounceTime(300),
        switchMap(value => this.userManagementService.pick(value))
      );
  }

  update() {
    const filter = JSON.parse(JSON.stringify(this.entries.filter || {}));
    this.turnoverManagementService.overview(this.entries.limit || 15, this.entries.offset || 0, this.sort, this.descending, filter).subscribe({
      next: (data: any) => {
        this.entries = data;
        this.entries.filter = filter;
      }, error: (error) => {
        this.entries = { error: error };
      }
    })
  }

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

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

  setInputFilter(key: string, target: EventTarget) {
    this.setFilter(key, (target as HTMLInputElement).value);
  }

  setFilter(key: string, value) {
    if (value != this.entries.filter[key]) {
      this.entries.filter[key] = value;
      this.entries.offset = 0;
      this.update();
    }
  }

}
