import { Component, OnInit } from "@angular/core";
import { BehaviorSubject, combineLatest, Subscription } from "rxjs";
import { switchMap, map } from "rxjs/operators";
import { StaffMemberService } from "../staff-member.service";

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

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

  ngOnInit(): void {
    this.staffMembers = [];
    this.isLoading = true;
    this.isError = false;
    this.sub = combineLatest([this.offset, this.limit])
      .pipe(
        switchMap(([off, limit]) =>
          this.staffMemberService.getStaffMembers({ _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(
        (staffMembers) => {
          this.staffMembers = staffMembers || [];
          this.isLoading = staffMembers == null;
          this.isError = false;
        },
        () => {
          this.staffMembers = [];
          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 getAverageRobotPrice(staffMember) {
    const prices = staffMember.robots.map((robot) => robot.price);
    const sum = prices.reduce((total, current) => total + current, 0);

    return prices.length > 0 ? sum / prices.length : 0;
  }

  public getBrandsExpertiseCount(staffMember) {
    const brandIds = staffMember.robots.map((robot) => robot.brandId);

    return new Set(brandIds).size;
  }

  public getAverageRobotFeatures(staffMember) {
    const featureCounts = staffMember.robots.map((robot) => robot.features.length);
    const sum = featureCounts.reduce((total, current) => total + current, 0);

    return featureCounts.length > 0 ? Math.ceil(sum / featureCounts.length) : 0;
  }

  public getAverageRobotExpertsCount(staffMember) {
    const staffMemberCounts = staffMember.robots.map((robot) => robot.experts.length);
    const sum = staffMemberCounts.reduce((total, current) => total + current, 0);

    return staffMemberCounts.length > 0 ? Math.round(sum / staffMemberCounts.length) : 0;
  }
}
