package manager

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

func managerConnected(mid string, conn *websocket.Conn) {
	utils.ManagerLock.Lock()
	utils.ManagerWss[mid] = conn
	utils.ManagerLock.Unlock()
	fmt.Printf("manager[%s] connected\n", mid)
}

func managerDisconnect(mid string) {
	utils.ManagerLock.Lock()
	delete(utils.ManagerWss, mid)
	utils.ManagerLock.Unlock()
	fmt.Printf("manager[%s] disconnected\n", mid)
}

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
	}
	var ok bool
	var mid string
	if mid, ok = ctx.GetQuery("token"); ok {
		if _, err = utils.Redis.Get(ctx, mid).Bool(); err != nil {  // better to get pub,pri secret here
			// token is invalid
		} else {
			// token is valid
		}
	} else {
		// no token
	}

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