package main

import (
	"fmt"
	"net/http"
	"time"
)

func ws(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("Upgrade error:", err)
		return
	}
	defer conn.Close()

	done := make(chan struct{})

	go func() {
		ticker := time.NewTicker(1 * time.Second)

		for {
			select {
			case <-done:
				return
			case t := <-ticker.C:
				msg := map[string]interface{}{
					"type":      "server_tick",
					"timestamp": t.Format(time.RFC3339),
				}

				if err := conn.WriteJSON(msg); err != nil {
					fmt.Println("Write error:", err)
					return
				}
			}
		}
	}()

	for {
		var msg Message
		err := conn.ReadJSON(&msg)
		if err != nil {
			fmt.Println("Read error:", err)
			break
		}
		fmt.Println(msg)

		// Send a response
		// response := fmt.Sprintf("Server time: %s", time.Now())
		// if err := conn.WriteMessage(websocket.TextMessage, []byte(response)); err != nil {
		// 	fmt.Println("Write error:", err)
		// 	break
		// }
	}
}
