package ws_gateway

import (
	"common/log"
	"common/net/socket"
	"fmt"
	ws_handler2 "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) {
	token, ok := conn.GetParam("token").(string)
	if !ok || token == "" {
		g.logger.Warnf("token is not string")
		_ = conn.Close()
		return
	}
	t, err := strconv.Atoi(token)
	if err != nil {
		_ = conn.Close()
	}
	if oldClient := ws_handler2.UserMgr.GetByUSN(int64(t)); oldClient != nil {
		oldClient.CloseClient()
	}
	client := ws_handler2.NewClient(int64(t), conn)
	ws_handler2.UserMgr.Add(int64(t), client)
	conn.SetParam("client", client)
}

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

func (g *GatewayWsServer) OnPong(conn socket.ISocketConn) {
	client, ok := conn.GetParam("client").(*ws_handler2.Client)
	if !ok || client.USN == 0 {
		return
	}
	client.OnEvent(&ws_handler2.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
}
