jpe-controle/FencerJudgeFront/src/app/services/matches/matches.service.ts
ExostFlash 39f23a3c80 test
2025-06-03 09:54:48 +02:00

182 lines
5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, BehaviorSubject, of } from 'rxjs';
import { Matches, MatchState } from '@interfaces/matches';
@Injectable({ providedIn: 'root' })
export class MatchesService {
private matches: Matches[] = [
{
id: 1,
refereeID: 10,
player1ID: 1,
score1: 15,
player2ID: 2,
score2: 13,
country: 'France',
city: 'Paris',
weapon: 'Fleuret',
date: new Date('2025-06-10T14:00:00'),
state: MatchState.OVER,
},
{
id: 2,
refereeID: 11,
player1ID: 3,
score1: 5,
player2ID: 4,
score2: 7,
country: 'France',
city: 'Lyon',
weapon: 'Épée',
date: new Date('2025-06-15T10:00:00'),
state: MatchState.ONGOING,
},
{
id: 3,
refereeID: 12,
player1ID: 5,
score1: 0,
player2ID: 6,
score2: 0,
country: 'Belgique',
city: 'Bruxelles',
weapon: 'Sabre',
date: new Date('2025-06-20T16:30:00'),
state: MatchState.NOT_STARTED,
},
];
private socket?: WebSocket;
private apiUrl = 'http://localhost:8080';
private matchUpdates$ = new Subject<Matches[]>();
private allMatches: Matches[] = [];
private nextMatchId = Math.max(...this.matches.map((m) => m.id)) + 1;
constructor(private http: HttpClient) {
this.sendCurrentMatches();
}
public sendCurrentMatches(): void {
if (!this.matches || this.matches.length === 0) {
console.warn('[HTTP] ⚠️ Aucun match à envoyer.');
return;
}
const headers = {
headers: {
'Content-Type': 'application/json',
},
};
this.matches.forEach((match) => {
this.http
.post(
this.apiUrl + '/matches/create-match',
JSON.stringify(match),
headers
)
.subscribe({
next: (response) => {
console.log('[HTTP] ✅ Match envoyé avec succès :', response);
},
error: (error) => {
console.error(
'[HTTP] ❌ Erreur lors de lenvoi dun match :',
error
);
},
});
});
}
private connectToMatchUpdatesWebSocket(): void {
const wsUrl = 'http://localhost:8080/ws';
this.socket = new WebSocket(wsUrl);
this.socket.onopen = () => {
console.log('[WebSocket] ✅ Connecté à', wsUrl);
};
this.socket.onmessage = (event) => {
try {
const data = JSON.parse(event.data) as Matches[];
console.log('[WebSocket] 📥 Données reçues :', data);
this.matchUpdates$.next(data);
} catch (e) {
console.error('[WebSocket] ❌ Erreur de parsing JSON', e);
}
};
this.socket.onerror = (err) => {
console.error('[WebSocket] ❌ Erreur :', err);
};
this.socket.onclose = () => {
console.warn('[WebSocket] 🔌 Fermeture de la connexion');
};
}
private sendMatchesToWebSocket(): void {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
const dataToSend = JSON.stringify(this.matches);
this.socket.send(dataToSend);
console.log('[WebSocket] 📤 Données envoyées :', dataToSend);
} else {
console.warn("[WebSocket] ⚠️ Le WebSocket n'est pas encore ouvert.");
}
}
getMatches(): Observable<Matches[]> {
return this.matchUpdates$.asObservable();
}
getMatchById(id: number): Observable<Matches | undefined> {
const match = this.allMatches.find((m) => m.id === id);
console.log(`[MatchesService] Match ID ${id} récupéré :`, match);
return new BehaviorSubject(match).asObservable();
}
updateMatch(id: number, updatedData: Partial<Matches>): void {
const matchIndex = this.allMatches.findIndex((m) => m.id === id);
if (matchIndex !== -1) {
const updatedMatch = { ...this.allMatches[matchIndex], ...updatedData };
this.allMatches[matchIndex] = updatedMatch;
this.matchUpdates$.next([...this.allMatches]); // émettre un nouveau tableau
console.log(
`[MatchesService] Match ${id} mis à jour localement :`,
updatedMatch
);
} else {
console.warn(`[MatchesService] Match ${id} non trouvé pour mise à jour`);
}
}
ngOnDestroy(): void {
this.socket?.close();
}
create(match: Omit<Matches, 'id'>): Observable<Matches> {
const newMatch: Matches = {
...match,
id: this.nextMatchId++,
};
this.matches.push(newMatch);
console.log('[MatchesService] Match created:', newMatch);
return of(newMatch);
}
deleteMatch(id: number): Observable<boolean> {
const index = this.matches.findIndex((m) => m.id === id);
if (index !== -1) {
const deletedMatch = this.matches.splice(index, 1)[0];
console.log(`[MatchesService] Match ${id} supprimé :`, deletedMatch);
return of(true);
} else {
console.warn(`[MatchesService] Match ${id} introuvable pour suppression`);
return of(false);
}
}
}