package socket

import (
	"blazing/common/socket/codec"
	"blazing/common/socket/errorcode"
	"blazing/logic/service"

	"github.com/gogf/gf/v2/util/gconv"
	"github.com/panjf2000/gnet/pkg/pool/goroutine"
	"github.com/panjf2000/gnet/v2"
)

func GetPlayer(c *service.Conn, userid uint32) *service.Player { //TODO 这里待优化,可能存在内存泄漏问题
	c.Mu.Lock()
	defer c.Mu.Unlock()
	//检查player初始化，是否为conn初始后取map，防止二次连接后存在两个player

	clientdata := c.MainConn.Context().(*service.ClientData)
	if clientdata.Player != nil {
		return clientdata.Player
	}

	clientdata.Player = service.NewPlayer(

		service.WithConn(c), //注入conn
	)

	// gff := socket.NewClientData()

	// gff.Player = clientdata.Player
	// c.MainConn.SetContext(gff)
	service.Mainplayer.Store(userid, clientdata.Player)

	return clientdata.Player
	//	return nil
}
func KickPlayer(userid uint32) { //踢出玩家
	//TODO 返回错误码
	//var player *entity.Player
	if player1, ok := service.Mainplayer.Load((userid)); ok {
		//取成功,否则创建
		head := service.NewTomeeHeader(1001, userid)
		head.Result = uint32(errorcode.ErrorCodes.ErrAccountLoggedInElsewhere)

		player1.SendPack(head.Pack(nil))
		player1.MainConn.MainConn.Close()
		//	clientdata.Player = player
	}

	//return player
	//	return nil
}

type Handler interface {
	Handle(gnet.Conn, []byte)
}
type Server struct {
	gnet.BuiltinEventEngine
	eng        gnet.Engine
	addr       string
	connected  int64
	network    string
	multicore  bool
	bufferSize int
	workerPool *goroutine.Pool
	codec      codec.SocketCodec
	handler    Handler
	discorse   bool
}

type Option func(*Server)

// NewServer returns a new Server

func NewServer(options ...Option) *Server {
	server := &Server{
		//	handler:    handler.NewTomeeHandler(),   //请求返回
		codec:      codec.NewTomeeSocketCodec(), //默认解码器 len+pack
		workerPool: goroutine.Default(),
		bufferSize: 4096, //默认缓冲区大小
		multicore:  true,
		discorse:   true,
	}
	for _, option := range options {
		option(server)
	}
	//...
	return server
}
func WithSocketCodec(codec codec.SocketCodec) Option {
	return func(u *Server) {
		u.codec = codec
	}
}
func WithCORS() Option {
	return func(u *Server) {
		u.discorse = false
	}
}
func WithSocketHandler(handler Handler) Option {
	return func(u *Server) {
		u.handler = handler
	}
}
func WithBufferSize(bufferSize int) Option {
	return func(u *Server) {
		u.bufferSize = bufferSize
	}
}
func WithPort(port int) Option {
	return func(s *Server) {

		s.network = "tcp"
		s.addr = ":" + gconv.String(port)
	}
}
