import {Component, inject} from '@angular/core';
import {HeaderComponent} from "@header/header.component";
import {map, Observable, shareReplay} from 'rxjs';
import {Player, TeamService} from '@api';
import {ScrollService} from '@services/scroll.service';
import {AsyncPipe, NgOptimizedImage} from '@angular/common';

@Component({
  selector: 'app-community',
  imports: [
    HeaderComponent,
    AsyncPipe,
    NgOptimizedImage
  ],
  templateUrl: './community.component.html',
  styleUrl: './community.component.scss'
})
export class CommunityComponent {
  private teamMembersCache: { [key: string]: Observable<Player[]> } = {};

  protected scrollService: ScrollService = inject(ScrollService)
  protected teamService: TeamService = inject(TeamService)

  public getTeamMembers(team: string): Observable<Player[]> {
    if (!this.teamMembersCache[team]) {
      this.teamMembersCache[team] = this.teamService.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`;
  }

  public toggledSections: string[] = [];

  public isToggled(section: string) {
    return this.toggledSections.includes(section);
  }

  public toggleSection(section: string) {
    if (this.isToggled(section)) {
      this.toggledSections = this.toggledSections.filter(s => s !== section);
    } else {
      this.toggledSections.push(section);
    }
  }

  public getTextForSection(section: string) {
    if (this.isToggled(section)) {
      return 'Hide Requirements...';
    } else {
      return 'Show Requirements...';
    }
  }
}
