package ws

import (
	"common/log"
	"common/proto/sc/sc_pb"
	"google.golang.org/protobuf/proto"
	"math"
	"math/rand"
	"sync"
	"time"
)

type EnterInstance struct {
}

func (_ *EnterInstance) Handle(data []byte, client *Client) {
	msg := &sc_pb.S2C_EnterInstance{}
	if err := proto.Unmarshal(data, msg); err != nil {
		log.Errorf("handle msg error")
		client.Stop()
		return
	}

	randDir := func() (float64, float64) {
		randX := float64(rand.Intn(201) - 100)
		randY := float64(rand.Intn(201) - 100)

		var normalizedX, normalizedY float64
		if length := math.Sqrt(randX*randX + randY*randY); length > 0 {
			normalizedX = randX / length
			normalizedY = randY / length
		}

		return normalizedX, normalizedY
	}

	go func() {
		for {
			x, y := randDir()
			_ = client.WriteMessage(sc_pb.MessageID_MESSAGE_ID_ACTION, &sc_pb.C2S_Action{
				Sequence:  0,
				Timestamp: 0,
				Action:    sc_pb.ActionID_ACTION_ID_MOVE,
				DirX:      int32(x * 100),
				DirY:      int32(y * 100),
				SkillID:   0,
			})
			time.Sleep(500 * time.Millisecond)
		}
	}()
}

var s2cPositionPool = sync.Pool{
	New: func() interface{} {
		return &sc_pb.Message{}
	},
}

type Position struct {
}

func (_ *Position) Handle(data []byte, client *Client) {
	//msg := s2cPositionPool.Get().(*sc_pb.Message)
	//if err := proto.Unmarshal(data, msg); err != nil {
	//	log.Errorf("handle msg error")
	//	client.Stop()
	//	return
	//}
	//s2cPositionPool.Put(msg)
}
