import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { PageEvent } from '@angular/material/paginator';
import { Sort } from '@angular/material/sort';
import { ActivatedRoute, Params, Router } from '@angular/router';
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,
    private router: Router,
    private route: ActivatedRoute
  ) { }


  ngOnInit(): void {
    this.turnovers = {};
    this.users = this.usersFormControl
      .valueChanges
      .pipe(
        debounceTime(300),
        switchMap(value => this.userManagementService.pick(value))
      );
    this.route.queryParams.subscribe({
      next: (params) => {
        this.turnovers = { filter: {} };
        if (params['l']) {
          this.turnovers.limit = +params['l'];
          if (this.turnovers.limit < 1) {
            this.turnovers.limit = 1;
          }
        }
        if (params['o']) {
          this.turnovers.offset = +params['o'];
          if (this.turnovers.offset < 0) {
            this.turnovers.offset = 0;
          }
        }

        if (params['s']) {
          this.sort = params['s'];
        }

        if (params['a']) {
          this.descending = false;
        } else {
          this.descending = true;
        }

        for (const param in params) {
          if (param != 'l' && param != 'o' && param != 's' && param != 'a') {
            this.filterOpen = true;
            this.turnovers.filter[param] = params[param];
            if (param == 'username') {
              this.usersFormControl.setValue(params[param]);
            }
          }
        }

        this.refresh();
      }
    });
  }

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

  update() {
    const filter = JSON.parse(JSON.stringify(this.turnovers.filter || {}));

    const params: Params = { l: null, o: null, s: null, a: null };

    if ((this.turnovers.limit || 15) != 15) {
      params['l'] = this.turnovers.limit;
    }

    if ((this.turnovers.offset || 0) != 0) {
      params['o'] = this.turnovers.offset;
    }

    if (this.sort != 'created') {
      params['s'] = this.sort;
    }

    if (!this.descending) {
      params['a'] = true;
    }

    if (filter) {
      for (const param in filter) {
        params[param] = filter[param] || null;
      }
    }

    this.router.navigate(
      [],
      {
        relativeTo: this.route,
        queryParams: params,
        queryParamsHandling: 'replace'
      });
  }

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