2024-10-19 09:47:56 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/pomodoro"
|
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"log"
|
2024-10-20 09:06:37 +00:00
|
|
|
"sync"
|
2024-10-19 09:47:56 +00:00
|
|
|
)
|
|
|
|
|
2024-10-20 09:06:37 +00:00
|
|
|
// Clients is a map of connected WebSocket clients, where each client is represented by the Client struct
|
|
|
|
var Clients = make(map[*websocket.Conn]*models.Client)
|
|
|
|
var mu sync.Mutex // Mutex to protect access to the Clients map
|
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
// handleClientCommands listens for commands from WebSocket clients and dispatches to the timer.
|
|
|
|
func handleClientCommands(ws *websocket.Conn) {
|
|
|
|
for {
|
|
|
|
_, message, err := ws.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Client disconnected: %v", err)
|
|
|
|
delete(Clients, ws)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle incoming commands
|
|
|
|
var command models.ClientCommand
|
|
|
|
err = json.Unmarshal(message, &command)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error unmarshalling command: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Process the command
|
|
|
|
switch command.Command {
|
|
|
|
case "start":
|
2024-10-20 16:08:12 +00:00
|
|
|
if !pomodoro.IsPomodoroOngoing() {
|
2024-10-19 09:47:56 +00:00
|
|
|
go pomodoro.RunPomodoroTimer(Clients) // Start the timer with the list of clients
|
|
|
|
}
|
|
|
|
case "stop":
|
2024-10-20 16:08:12 +00:00
|
|
|
if pomodoro.IsPomodoroOngoing() {
|
2024-10-20 08:02:00 +00:00
|
|
|
pomodoro.ResetPomodoro(Clients) // Reset Pomodoro
|
2024-10-19 16:15:16 +00:00
|
|
|
}
|
|
|
|
case "pause":
|
2024-10-20 16:08:12 +00:00
|
|
|
if pomodoro.IsPomodoroOngoing() && !pomodoro.IsPomodoroPaused() {
|
2024-10-19 16:15:16 +00:00
|
|
|
pomodoro.PausePomodoro() // Pause the timer
|
|
|
|
}
|
|
|
|
case "resume":
|
2024-10-20 16:08:12 +00:00
|
|
|
if pomodoro.IsPomodoroOngoing() && pomodoro.IsPomodoroPaused() {
|
2024-10-19 16:15:16 +00:00
|
|
|
pomodoro.ResumePomodoro() // Resume the timer
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|
|
|
|
}
|
2024-10-19 16:15:16 +00:00
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|
|
|
|
}
|