tgd-frontend/src/app/components/participants/participants.component.ts
2024-10-29 22:39:42 +04:00

83 lines
2.5 KiB
TypeScript

import {ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnDestroy, OnInit} from '@angular/core';
import {ApiService} from "../../services/api.service";
import {Participant} from "../../../types/participant";
import {EventService} from "../../services/event.service";
import {map, takeUntil} from "rxjs/operators";
import {Subject} from "rxjs";
@Component({
selector: 'app-participants',
templateUrl: './participants.component.html',
styleUrls: ['./participants.component.scss'],
changeDetection: ChangeDetectionStrategy.Default
})
export class ParticipantsComponent implements OnInit, OnDestroy {
@Input() small = false;
@Input() sorted = false;
@Input() showScoreOnSmall = false;
participants: Participant[] = [];
destroyed$ = new Subject<void>();
constructor(private apiService: ApiService, private eventService: EventService, private changeDetector: ChangeDetectorRef) { }
ngOnInit(): void {
this.eventService.userAddedEvent.pipe(
takeUntil(this.destroyed$),
map(e => e.data),
).subscribe(e => this.updateParticipants());
this.eventService.scoreChangedEvent.pipe(
takeUntil(this.destroyed$),
map(e => e.data),
).subscribe(data => {
const player = this.participants.find(x => x.telegramId === data.telegramId);
if (player) {
player.score = data.newScore
}
})
this.eventService.userPropertyChanged.pipe(takeUntil(this.destroyed$)).subscribe(r => {
if(r.data.property === "bannedFor") {
const p = this.participants.find(x => x.telegramId === +r.data.user);
console.log(p);
if(p && +r.data.value > 0) {
console.log(`set banned`);
p.banned = true;
p.bannedRemaining = +r.data.value;
console.log(p);
} else if(p) {
p.banned = false;
p.bannedRemaining = +r.data.value;
}
} else {
console.log('not banned');
}
})
this.updateParticipants();
}
updateParticipants() {
this.apiService.getParticipants().subscribe((r) => {
if (!this.sorted) {
this.participants = r;
} else {
this.participants = r.sort((a,b) => {
if (a.score === undefined || b.score === undefined) {
return 0;
}
if (a.score < b.score) {
return -1;
}
if (a.score > b.score) {
return 1;
}
return 0;
}).reverse();
}
});
this.changeDetector.markForCheck();
}
ngOnDestroy() {
this.destroyed$.complete();
}
}