package ws_gateway

import (
	"common/log"
	"common/net/socket"
	"common/utils"
	"fmt"
	"gateway/internal/handler/ws_handler"
	"go.uber.org/zap"
	"strconv"
	"time"
)

type GatewayWsServer struct {
	logger *zap.SugaredLogger
}

func (g *GatewayWsServer) OnOpen(conn socket.ISocketConn) ([]byte, socket.Action) {
	g.logger = log.GetLogger().Named(fmt.Sprintf("addr:%v", conn.RemoteAddr()))
	return nil, socket.None
}

func (g *GatewayWsServer) OnHandShake(conn socket.ISocketConn, bytes []byte, callback func(conn socket.ISocketConn, bytes []byte)) socket.Action {
	token, ok := conn.GetParam("token").(string)
	if !ok {
		g.logger.Warnf("token is not string")
		return socket.Close
	}
	//claims, err := utils.ParseToken(token, config.Get().Auth.Secret)
	//if err != nil {
	//	g.logger.Warnf("token is invalid")
	//	return socket.Close
	//}

	t, _ := strconv.Atoi(token)
	claims := utils.Claims{
		USN: int64(t),
	}
	go func(shResp []byte) {
		if oldClient := ws_handler.UserMgr.GetByUSN(claims.USN); oldClient != nil {
			oldClient.CloseClient()
		}
		client := ws_handler.NewClient(claims.USN, conn)
		ws_handler.UserMgr.Add(claims.USN, client)
		conn.SetParam("client", client)
		callback(conn, shResp)
	}(bytes)
	return socket.None
}

func (g *GatewayWsServer) OnMessage(conn socket.ISocketConn, bytes []byte) socket.Action {
	client, ok := conn.GetParam("client").(*ws_handler.Client)
	if !ok || client.USN == 0 {
		return socket.Close
	}
	client.OnEvent(&ws_handler.ClientEvent{Msg: bytes})
	return socket.None
}

func (g *GatewayWsServer) OnPong(conn socket.ISocketConn) {
	client, ok := conn.GetParam("client").(*ws_handler.Client)
	if !ok || client.USN == 0 {
		return
	}
	client.OnEvent(&ws_handler.PongEvent{})
}

func (g *GatewayWsServer) OnClose(_ socket.ISocketConn, _ error) socket.Action {
	return socket.Close
}

func (g *GatewayWsServer) OnTick() (time.Duration, socket.Action) {
	return 5 * time.Second, socket.None
}
