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 21:09:30 +00:00
|
|
|
var unsetPomodoroConfig models.GoTomatoPomodoroConfig // used to check if client passed a config json
|
|
|
|
|
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 {
|
2024-10-20 21:09:30 +00:00
|
|
|
var clientCommand models.ClientCommand
|
|
|
|
var pomodoroConfig = models.GoTomatoPomodoroConfig{
|
|
|
|
Work: 25 * 60,
|
|
|
|
ShortBreak: 5 * 60,
|
|
|
|
LongBreak: 15 * 60,
|
|
|
|
Sessions: 4,
|
|
|
|
}
|
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
_, message, err := ws.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Client disconnected: %v", err)
|
2024-10-21 07:20:58 +00:00
|
|
|
delete(Clients, ws)
|
2024-10-19 09:47:56 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle incoming commands
|
2024-10-20 21:09:30 +00:00
|
|
|
err = json.Unmarshal(message, &clientCommand)
|
2024-10-19 09:47:56 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error unmarshalling command: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Process the command
|
2024-10-20 21:09:30 +00:00
|
|
|
switch clientCommand.Command {
|
2024-10-19 09:47:56 +00:00
|
|
|
case "start":
|
2024-10-20 16:08:12 +00:00
|
|
|
if !pomodoro.IsPomodoroOngoing() {
|
2024-10-20 21:09:30 +00:00
|
|
|
if clientCommand.Config != unsetPomodoroConfig {
|
|
|
|
pomodoroConfig = clientCommand.Config
|
|
|
|
}
|
2024-10-21 06:39:39 +00:00
|
|
|
go pomodoro.RunPomodoro(pomodoroConfig) // Start the timer with the list of clients
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|
|
|
|
case "stop":
|
2024-10-20 16:08:12 +00:00
|
|
|
if pomodoro.IsPomodoroOngoing() {
|
2024-10-21 06:39:39 +00:00
|
|
|
pomodoro.ResetPomodoro() // 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
|
|
|
}
|
|
|
|
}
|