package debugger

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

func debuggerConnect(did string, conn *websocket.Conn) {
	utils.DebugLock.Lock()
	utils.DebugWss[did] = conn
	utils.DebugLock.Unlock()
	utils.Logger.Printf("debugger[%s] connected\n", did)
}

func debuggerDisconnect(did string) {
	utils.DebugLock.Lock()
	delete(utils.DebugWss, did)
	utils.DebugLock.Unlock()
	utils.Logger.Printf("debugger[%s] disconnected\n", did)
}

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

	debuggerConnect(who, conn)
	for {
		var msg utils.WsMsg
		err = conn.ReadJSON(&msg)
		if err != nil {
			debuggerDisconnect(who)
			return
		}
		switch msg.Event {
		case "pin":
			keepAlive(conn)
			break
		case "listDevices":
			listDevices(conn)
			break
		case "setDebug":
			setDebug(conn, msg.Data)
			break
		case "openGate":
			openGate(conn, who, msg.Data)
			break
		case "setLocation":
			setLocation(conn, msg.Data)
			break
		case "setPpv":
			setPpv(conn, msg.Data)
			break
		default:
			_ = conn.WriteJSON(utils.WsError("unrecognized event"))
			break
		}
	}
}
