From fe1e2b8eb0ee6ee64517dd9cff4a0374e0d8f201 Mon Sep 17 00:00:00 2001
From: "narindra.rajohnso" <narindra-hasimanjaka-david.rajohnson@etu.hesge.ch>
Date: Fri, 9 Jun 2023 15:32:36 +0200
Subject: [PATCH] add players ready logic and fetch the begin question

---
 .../src/app/homepage/homepage.component.html  | 30 ++++++++---
 .../src/app/homepage/homepage.component.ts    | 15 +++---
 .../quizz-play/quizz-play.component.html      | 32 ++++++++++-
 .../quizz-play/quizz-play.component.ts        | 26 ++++++++-
 .../src/app/homepage/quizz.service.ts         | 54 ++++++++++++++++++-
 .../waiting-players.component.html            |  7 +++
 .../waiting-players.component.ts              | 24 ++++++---
 .../quizz-game/src/app/login/session-model.ts |  4 +-
 .../app/login/sign-in/sign-in.component.ts    |  2 +-
 9 files changed, 166 insertions(+), 28 deletions(-)

diff --git a/Frontend/quizz-game/src/app/homepage/homepage.component.html b/Frontend/quizz-game/src/app/homepage/homepage.component.html
index e498d99..a290fd7 100644
--- a/Frontend/quizz-game/src/app/homepage/homepage.component.html
+++ b/Frontend/quizz-game/src/app/homepage/homepage.component.html
@@ -1,19 +1,35 @@
 <div class="flex h-screen">
   <div class="w-1/4 flex h-screen flex-col justify-between border-e bg-white">
 
-    <div class="bg-white p-8">
-      <h1 class="text-2xl font-bold mb-4">Joueurs Connectés</h1>
-      <ul class="text-gray-600">
-        <li *ngFor="let player of players" class="mb-2">{{ player.firstname }} {{ player.lastname }}</li>
+    <div class="flex flex-col space-y-4">
+      <h2 class="text-lg font-bold">Joueurs connectés</h2>
+
+
+      <ul class="max-w-md divide-y divide-gray-200 dark:divide-gray-700">
+        <li class="pb-3 sm:pb-4" *ngFor="let player of players">
+          <div class="flex items-center space-x-4">
+            <div class="flex-1 pl-2.5 min-w-0">
+              <p class="text-sm font-medium text-gray-900 truncate dark:text-white">
+                {{ player.firstname }} {{ player.lastname }}
+              </p>
+              <p class="text-sm text-gray-500 truncate dark:text-gray-400">
+                {{ player.username }}
+              </p>
+            </div>
+            <div class="inline-flex pr-2.5 items-center text-base font-semibold text-gray-900 dark:text-white">
+              <span [ngClass]="{'bg-green-500': player.ready, 'bg-red-500': !player.ready}" class="w-2 h-2 rounded-full"></span>
+            </div>
+          </div>
+        </li>
       </ul>
-      <ng-container *ngIf="players.length === 3">
-        <p class="text-green-500 mt-4">Tous les joueurs sont connectés ! La partie peut commencer.</p>
-      </ng-container>
+
+
     </div>
 
 
 
 
+
   </div>
   <div class="w-3/4 h-screen">
     <router-outlet></router-outlet>
diff --git a/Frontend/quizz-game/src/app/homepage/homepage.component.ts b/Frontend/quizz-game/src/app/homepage/homepage.component.ts
index 58929bd..8099c4e 100644
--- a/Frontend/quizz-game/src/app/homepage/homepage.component.ts
+++ b/Frontend/quizz-game/src/app/homepage/homepage.component.ts
@@ -1,8 +1,8 @@
 import {Component, OnInit} from '@angular/core';
-import {User} from "../manage/users/user-model";
 import {ActivatedRoute, Router} from "@angular/router";
 import {QuizzService} from "./quizz.service";
 import {SessionService} from "../login/session.service";
+import {Session} from "../login/session-model";
 
 @Component({
   selector: 'app-homepage',
@@ -11,7 +11,7 @@ import {SessionService} from "../login/session.service";
 })
 export class HomepageComponent implements OnInit {
   loading=false;
-  players: User[]= [];
+  players: Session[]= [];
 
   constructor(private sessionService: SessionService, private actRoute: ActivatedRoute, private quizzService: QuizzService, private router: Router) {
   }
@@ -25,17 +25,20 @@ export class HomepageComponent implements OnInit {
       }
       this.quizzService.username = paramM.get('username')!!;
       console.log(this.quizzService.username);
+      this.quizzService.players.subscribe((players)=>{
+        this.players=players;
+      });
 
     })
+    //this.players.push(new Session("test", "voila", "moi"));
+
   }
-    //this.players.push(new User("test", "voila", "moi", "sdfg@sdf.th", "user", "fsfdss"));
   logOut(){
     this.router.navigate(['/', 'login']);
     //this.sessionService.deleteToken();
+    this.quizzService.socket.emit("player-not-ready");
     this.quizzService.socket.disconnect();
   }
 
-  onUserConnect(user:User){
-    this.players.push(user);
-  }
+
 }
diff --git a/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.html b/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.html
index d4ff39b..5792c59 100644
--- a/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.html
+++ b/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.html
@@ -1 +1,31 @@
-<p>quizz-play works!</p>
+<div class="max-w-md mx-auto bg-white rounded shadow p-6">
+  <h2 class="text-2xl font-bold mb-4">Question du quizz</h2>
+
+  <p class="text-lg mb-4">Quelle est la capitale de la France ?</p>
+
+  <div class="space-y-4">
+    <div class="flex items-center">
+      <input type="radio" id="reponse1" name="reponse" class="form-radio text-indigo-600 h-4 w-4" />
+      <label for="reponse1" class="ml-2 text-gray-700">Paris</label>
+    </div>
+
+    <div class="flex items-center">
+      <input type="radio" id="reponse2" name="reponse" class="form-radio text-indigo-600 h-4 w-4" />
+      <label for="reponse2" class="ml-2 text-gray-700">Londres</label>
+    </div>
+
+    <div class="flex items-center">
+      <input type="radio" id="reponse3" name="reponse" class="form-radio text-indigo-600 h-4 w-4" />
+      <label for="reponse3" class="ml-2 text-gray-700">Berlin</label>
+    </div>
+
+    <div class="flex items-center">
+      <input type="radio" id="reponse4" name="reponse" class="form-radio text-indigo-600 h-4 w-4" />
+      <label for="reponse4" class="ml-2 text-gray-700">Madrid</label>
+    </div>
+  </div>
+
+  <button class="mt-6 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded">
+    Valider
+  </button>
+</div>
diff --git a/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.ts b/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.ts
index 5308be1..cee86d1 100644
--- a/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.ts
+++ b/Frontend/quizz-game/src/app/homepage/quizz-play/quizz-play.component.ts
@@ -1,10 +1,32 @@
-import { Component } from '@angular/core';
+import {Component, OnInit} from '@angular/core';
+import {Subscription} from "rxjs";
+import {ManageService} from "../../manage/manage.service";
+import {Question} from "../../manage/questions/question-model";
+import {QuizzService} from "../quizz.service";
 
 @Component({
   selector: 'app-quizz-play',
   templateUrl: './quizz-play.component.html',
   styleUrls: ['./quizz-play.component.css']
 })
-export class QuizzPlayComponent {
+export class QuizzPlayComponent implements OnInit{
+  question!: Question;
+  loadingQuestion!:boolean;
+  constructor(private quizzService: QuizzService) {
+  }
+
+  ngOnInit() {
+    this.loadingQuestion=true;
+    this.quizzService.socket.emit("on-game")
+    this.quizzService.socket.on("question", (question)=>{
+      this.question=question;
+      console.log(this.question);
+      this.loadingQuestion=false;
+    });
+
+
+  }
+
+
 
 }
diff --git a/Frontend/quizz-game/src/app/homepage/quizz.service.ts b/Frontend/quizz-game/src/app/homepage/quizz.service.ts
index 6957542..c2ff93b 100644
--- a/Frontend/quizz-game/src/app/homepage/quizz.service.ts
+++ b/Frontend/quizz-game/src/app/homepage/quizz.service.ts
@@ -1,5 +1,5 @@
 import { Injectable } from '@angular/core';
-import {BehaviorSubject, Subject} from "rxjs";
+import {BehaviorSubject, map, Subject, tap} from "rxjs";
 import {HttpClient} from "@angular/common/http";
 import {Session} from "../login/session-model";
 import {SessionService} from "../login/session.service";
@@ -46,11 +46,13 @@ export class QuizzService {
       this.httpClient.get<any>('http://localhost:30992/api/v1/gamer/' + this.username).subscribe(
         response => {
           this._userInfo=new Session(
+            response.access_user.username,
             response.access_user.firstname,
             response.access_user.lastname
           )
           this.userInfoSubject.next(this.userInfo);
           this.connetToSocketIo();
+          this.getNbPlayers();
           resolve(this._userInfo);
         },
         error => {
@@ -64,10 +66,58 @@ export class QuizzService {
     const token = this.sessionService.token;
     this._socket= io('http://localhost:30992', {
       auth: {
-        token: token // Inclure le JWT dans la requête d'authentification
+        token: token
       }
     });
   }
 
+  getNbPlayers(){
+    this.socket.on('players', (players) => {
+      console.log("players: ", players);
+      this._players.next(players);
+    });
+  }
+
+  onPlayerReady(){
+    this.socket.on("ready-player", (username)=>{
+      console.log("ready-player: ", username);
+      this.players.pipe(
+        // Utilisez l'opérateur map pour itérer sur chaque élément du tableau
+        map((players: Session[]) => {
+          return players.map(player => {
+            if (player.username === username) {
+              player.ready = true;
+            }
+            return player;
+          });
+        }),
+        tap(playersUpdated => {
+          this._players.next(playersUpdated);
+        })
+      ).subscribe();
+    })
+  }
+  onPlayerNotReady(){
+    this.socket.on("not-ready-player", (username)=>{
+      console.log("not-ready-player: ", username);
+      this.players.pipe(
+        // Utilisez l'opérateur map pour itérer sur chaque élément du tableau
+        map((players: Session[]) => {
+          return players.map(player => {
+            if (player.username === username) {
+              player.ready = false;
+            }
+            return player;
+          });
+        }),
+        tap(playersUpdated => {
+          this._players.next(playersUpdated);
+        })
+      ).subscribe();
+    })
+  }
+
+
+
 
 }
diff --git a/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.html b/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.html
index 9084e14..fd42e95 100644
--- a/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.html
+++ b/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.html
@@ -15,6 +15,13 @@
     </div>
     <div *ngIf="gameBegin">
       <h2 class="text-2xl font-bold mb-4">Le jeu peut maintenant commencé</h2>
+      <div class="relative">
+        <button (click)="playGame()"
+                [disabled]="waitConfirmPlayer"
+          class="absolute top-0 right-0 px-4 py-2 bg-blue-500 text-white font-semibold rounded disabled:opacity-50">
+          {{waitConfirmPlayer?"Attente confirmation joueurs": "Jouer"}}
+        </button>
+      </div>
     </div>
 
   </div>
diff --git a/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.ts b/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.ts
index e92c4a3..a0c4895 100644
--- a/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.ts
+++ b/Frontend/quizz-game/src/app/homepage/waiting-players/waiting-players.component.ts
@@ -14,6 +14,7 @@ export class WaitingPlayersComponent implements OnInit, OnDestroy{
   userInfo!: Session;
   userSub!: Subscription;
   loading!: boolean;
+  waitConfirmPlayer=false;
   private startGameSubscription!: any;
   private playersLeftSub!:any;
   gameBegin!:boolean;
@@ -38,6 +39,12 @@ export class WaitingPlayersComponent implements OnInit, OnDestroy{
           console.log("start game");
           this.gameBegin=true;
         });
+        this.quizzService.onPlayerReady();
+        this.quizzService.onPlayerNotReady();
+        this.quizzService.socket.on("game-ready-start", ()=>{
+          console.log("game is ready to start");
+          this.router.navigate(["/"+userInfo.username+"/play/quizz-play"]);
+        })
       }
       this.loading=false;
 
@@ -48,23 +55,24 @@ export class WaitingPlayersComponent implements OnInit, OnDestroy{
         alert("Votre session a expiré, veuillez vous reconnecter");
         this.router.navigate(['/', 'login']);
         //this.sessionService.deleteToken();
-        this.quizzService.socket.disconnect();
+        if(this.quizzService.socket) {
+          this.quizzService.socket.emit("player-not-ready")
+          this.quizzService.socket.disconnect();
+        }
       }
     })
   }
 
+  playGame(){
+    this.waitConfirmPlayer=true;
+    this.quizzService.socket.emit("player-ready");
+  }
+
 
 
   ngOnDestroy() {
     if(this.userSub)
       this.userSub.unsubscribe();
-    /*
-    if(this.startGameSubscription)
-        this.startGameSubscription.unsubscribe();
-    if(this.playersLeftSub)
-      this.playersLeftSub.unsubscribe();
-
-     */
   }
 
 }
diff --git a/Frontend/quizz-game/src/app/login/session-model.ts b/Frontend/quizz-game/src/app/login/session-model.ts
index 1039275..52700c4 100644
--- a/Frontend/quizz-game/src/app/login/session-model.ts
+++ b/Frontend/quizz-game/src/app/login/session-model.ts
@@ -1,6 +1,8 @@
 export class Session {
   constructor(
+    public username: string,
     public firstname: string,
-    public lastname: string
+    public lastname: string,
+    public ready?: boolean
   ) {}
 }
diff --git a/Frontend/quizz-game/src/app/login/sign-in/sign-in.component.ts b/Frontend/quizz-game/src/app/login/sign-in/sign-in.component.ts
index 45b29ab..b8a5753 100644
--- a/Frontend/quizz-game/src/app/login/sign-in/sign-in.component.ts
+++ b/Frontend/quizz-game/src/app/login/sign-in/sign-in.component.ts
@@ -44,7 +44,7 @@ export class SignInComponent implements OnInit{
       response => {
         console.log("reponse sign in:", response);
         this.sessionService.token=response.token;
-        this.sessionService.session=new Session(response.firstname, response.lastname);
+        this.sessionService.session=new Session(username, response.firstname, response.lastname);
         if(response.message === "USER_ALLOWED"){
           this.router.navigate(['/'+username+'/play']);
         }
-- 
GitLab