import { Component, 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 { TurnoverService } from 'src/app/services/turnover.service';
import { UserManagementService } from 'src/app/services/user.management.service';

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

  turnovers: any;
  overview: any[];
  sort: string = "created";
  descending: boolean = true;
  filterOpen: boolean = false;

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

  constructor(
    private turnoverService: TurnoverService
  ) { }

  ngOnInit(): void {
    this.turnovers = {};
    this.update();
  }

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

    this.turnoverService.overview(this.turnovers.limit || 15, this.turnovers.offset || 0, this.sort, this.descending, this.turnovers.filter).subscribe({
      next: (data: any) => {
        this.overview = data;
        if (!this.overview) {
          this.overview = ['', 0, 0];
        }
      }, error: (error) => {
        this.turnovers = { error: error };
      }
    })
  }

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

  applySort(event: Sort) {
    this.sort = event.direction ? event.active : 'created';
    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.turnovers.filter[key]) {
      this.turnovers.filter[key] = value;
      this.turnovers.offset = 0;
      this.update();
    }
  }
}
