import { Component, OnDestroy, OnInit } from "@angular/core";
import { BehaviorSubject, combineLatest, Observable, Subscription } from "rxjs";
import { concatMap, map, mergeMap, switchMap, tap, withLatestFrom } from "rxjs/operators";
import { ClientService } from "../clients.service";

@Component({
  selector: "app-clients-list",
  templateUrl: "./clients-list.component.html",
  styleUrls: ["./clients-list.component.scss"],
})
export class ClientsListComponent implements OnInit, OnDestroy {
  public clients = [];
  public isLoading = true;
  public isError = false;
  private sub: Subscription;
  private offset: BehaviorSubject<number>;
  private limit: BehaviorSubject<number>;

  constructor(private readonly clientService: ClientService) {
    this.offset = new BehaviorSubject(0);
    this.limit = new BehaviorSubject(20);
  }

  ngOnDestroy(): void {
    this.sub.unsubscribe();
  }

  ngOnInit(): void {
    this.clients = [];
    this.isLoading = true;
    this.isError = false;
    this.sub = combineLatest([this.offset, this.limit])
      .pipe(
        switchMap(([off, limit]) =>
          this.clientService.getClients({ _limit: limit, _offset: off * limit })
        ),
        map((data) =>
          data
            ? data.slice(
                this.offset.value * this.limit.value,
                (this.offset.value + 1) * this.limit.value
              )
            : null
        ),
        map((data) => (data && data.length ? data : null))
      )
      .subscribe(
        (clients) => {
          this.clients = clients || [];
          this.isLoading = clients == null;
          this.isError = false;
        },
        () => {
          this.clients = [];
          this.isLoading = false;
          this.isError = true;
        }
      );
  }

  changePage(num) {
    this.offset.next(this.offset.value + num);
  }

  changeLimit(limit) {
    this.limit.next(limit);
    this.offset.next(0);
  }
}
