package seller

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

func sellerConnected(seq string, conn *websocket.Conn) *tables.DeviceTable {
	device := tables.DeviceTable{Id: seq}
	err := device.Get()
	if err == sql.ErrNoRows { // insert new device
		err = device.Insert()
		if err != nil {
			_ = conn.WriteJSON(utils.WsError("New device join failed"))
			return nil
		}
		_ = device.Get()
	} else { // update last time
		device.Last = utils.TimeNow()
		err = device.Update(utils.JsonType{"last": device.Last})
		if err != nil {
			_ = conn.WriteJSON(utils.WsError("Update last active time failed"))
			return nil
		}
	}

	utils.SellerLock.Lock()
	utils.SellerWss[seq] = conn
	utils.SellerLock.Unlock()
	fmt.Printf("device connected: %s\n", seq)
	return &device
}

func sellerDisconnect(seq string) {
	utils.SellerLock.Lock()
	delete(utils.SellerWss, seq)
	utils.SellerLock.Unlock()
	fmt.Printf("device[%s] disconnected\n", seq)
}

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
	}
	seq := ctx.Param("seq")  //ctx.DefaultQuery("seq", "")
	if seq == "" {
		_ = conn.WriteJSON(utils.WsError("device seq is required"))
		return
	}

	device := sellerConnected(seq, conn)
	if device == nil {
		return
	}
	infoOfDevice(device, conn)
	for {
		var msg utils.WsMsg
		err = conn.ReadJSON(&msg)
		if err != nil {
			sellerDisconnect(seq)
			return
		}
		switch msg.Event {
		case "setLocation":
			updateLocation(device, conn, msg.Data)
			break
		case "getQrcode":
			getQrcode(conn, msg.Data)
			break
		case "checkAuthCode":
			checkAuthCode(conn, device.Id, msg.Data)
			break
		case "openResult":
			openResult(conn, msg.Data)
			break
		case "workFinished":
			workFinished(conn, msg.Data)
			break
		default:
			_ = conn.WriteJSON(utils.WsError("unrecognized event"))
			break
		}
	}
}
