import {Component} from '@angular/core';
import {ScrollService} from '@services/scroll.service';
import {Player, TeamService} from '@api';
import {CommonModule, NgOptimizedImage} from '@angular/common';
import {HeaderComponent} from '@header/header.component';
import {CookieService} from 'ngx-cookie-service';
import {map, Observable, shareReplay} from 'rxjs';

@Component({
  selector: 'app-team',
  standalone: true,
  imports: [
    CommonModule,
    HeaderComponent,
    NgOptimizedImage
  ],
  providers: [
    CookieService,
  ],

  templateUrl: './team.component.html',
  styleUrl: './team.component.scss'
})
export class TeamComponent {

  private teamMembersCache: { [key: string]: Observable<Player[]> } = {};

  constructor(public scrollService: ScrollService, public teamApi: TeamService) {
  }

  public getTeamMembers(team: string): Observable<Player[]> {
    if (!this.teamMembersCache[team]) {
      this.teamMembersCache[team] = this.teamApi.getTeamMembers(team).pipe(
        map(res => this.removeDuplicates(res)),
        shareReplay(1)
      );
    }
    return this.teamMembersCache[team];
  }

  private removeDuplicates(array: Player[]): Player[] {
    return array.filter((player, index, self) =>
      index === self.findIndex((p) => p.uuid === player.uuid)
    );
  }

  public getAvatarUrl(entry: Player): string {
    let uuid = entry.uuid.replace('-', '');
    return `https://crafatar.com/avatars/${uuid}?overlay`;
  }
}
