package worker

import (
	"Wine-Server/utils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

func workerConnected(wid string, conn *websocket.Conn) {
	utils.WorkerLock.Lock()
	utils.WorkerWss[wid] = conn
	utils.WorkerLock.Unlock()
	utils.Logger.Printf("worker[%s] connected\n", wid)
}

func workerDisconnect(wid string) {
	utils.WorkerLock.Lock()
	delete(utils.WorkerWss, wid)
	utils.WorkerLock.Unlock()
	utils.Logger.Printf("worker[%s] disconnected\n", wid)
}

func SocketHandler(ctx *gin.Context) {
	conn, err := utils.UpgradeHttp2Ws.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		ctx.JSON(utils.HttpError, utils.Fail("can't establish socket connect"))
		return
	}
	wid := ctx.Param("wid")
	if wid == "" {
		_ = conn.WriteJSON(utils.WsError("worker id is required"))
		return
	}

	workerConnected(wid, conn)
	for {
		var msg utils.WsMsg
		err = conn.ReadJSON(&msg)
		if err != nil {
			workerDisconnect(wid)
			return
		}
		switch msg.Event {
		case "openGate":
			openGate(conn, wid, msg.Data)
			break
		case "orderFinished":
			orderFinished(conn, msg.Data)
			break
		default:
			_ = conn.WriteJSON(utils.WsError("unrecognized event"))
			break
		}
	}
}
