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

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

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

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

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


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

  update() {
    const filter = JSON.parse(JSON.stringify(this.turnovers.filter || {}));
    this.turnoverManagementService.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 };
      }
    })
  }

  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();
    }
  }
}
