import { Component, OnDestroy, OnInit } from "@angular/core";
import { BehaviorSubject, combineLatest, Observable, Subscription } from "rxjs";
import { map, switchMap } from "rxjs/operators";
import { RobotService } from "../robot.service";

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

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

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

  ngOnInit(): void {
    this.robots = [];
    this.isLoading = true;
    this.isError = false;
    this.sub = combineLatest([this.offset, this.limit])
      .pipe(
        switchMap(([off, limit]) =>
          this.robotService.getRobots({ _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(
        (robots) => {
          this.robots = robots || [];
          this.isLoading = robots == null;
          this.isError = false;
        },
        () => {
          this.robots = [];
          this.isLoading = false;
          this.isError = true;
        }
      );
  }

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

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

  public getBadgeClass(robot) {
    switch (robot.type) {
      case "cleaning":
        return { "badge-secondary": true };
      case "kitchen":
        return { "badge-success": true };
      default:
        return { "badge-primary": true };
    }
  }
}
