From 1f101fe7cc5cc31c66146a1e226fa4bae805fdd4 Mon Sep 17 00:00:00 2001
From: Leonardo Bishop <me@leonardobishop.com>
Date: Thu, 9 Nov 2023 00:17:03 +0000
Subject: Refactor websockets

---
 frontend/src/views/JoinView.vue | 43 +++++++++++++++++++++++++++--------------
 1 file changed, 28 insertions(+), 15 deletions(-)

(limited to 'frontend/src/views/JoinView.vue')

diff --git a/frontend/src/views/JoinView.vue b/frontend/src/views/JoinView.vue
index 83421ee..d081512 100644
--- a/frontend/src/views/JoinView.vue
+++ b/frontend/src/views/JoinView.vue
@@ -10,20 +10,35 @@ const connected = ref(false);
 const gameState = ref('');
 const controlsLocked = ref(false);
 
-const socket = new WebSocket(`${import.meta.env.VITE_BACKEND_WS_URL}`);
-socket.onopen = () => {
-  socket.send(JSON.stringify({
-    action: 'join',
-    sessionId: sessionId,
-  }));
-};
+let moveTimeout: number;
+
+const socket = new WebSocket(`${import.meta.env.VITE_BACKEND_WS_URL}/coop?action=join&sessionId=${sessionId}`);
 socket.onmessage = (event) => {
   const data = JSON.parse(event.data);
-  if (data.action === 'state') {
-    gameState.value = data.state;
+  const type = data.type;
+  const payload = data.payload;
+
+  if (type === 'state') {
+    gameState.value = payload.state;
     joiningGame.value = false;
     connected.value = true;
   }
+
+  if (type === 'timeout') {
+    const timeout = payload.timeoutUntil - Date.now();
+    if (timeout < 0) {
+      controlsLocked.value = false;
+      return;
+    }
+
+    controlsLocked.value = true; 
+    if (moveTimeout) {
+      clearTimeout(moveTimeout);
+    }
+    moveTimeout = setTimeout(() => {
+      controlsLocked.value = false;
+    }, timeout);
+  }
 };
 
 function sendMove(move: string) {
@@ -31,13 +46,11 @@ function sendMove(move: string) {
     return;
   }
   controlsLocked.value = true;
-  setTimeout(() => {
-    controlsLocked.value = false;
-  }, 1000);
   socket.send(JSON.stringify({
-    action: 'move',
-    sessionId: sessionId,
-    move: move,
+    type: 'move',
+    payload: {
+      move 
+    }
   }));
 }
 
-- 
cgit v1.2.3-70-g09d2

