package ws_handler

import (
	"common/net/grpc/service"
	"common/proto/sc/sc_pb"
	"common/proto/ss/grpc_pb"
	"gateway/internal/grpc_server/stream_client"
	"google.golang.org/protobuf/proto"
	"time"
)

func (c *Client) handle(event Event) {
	switch e := event.(type) {
	case *ClientEvent:
		msg := &sc_pb.Message{}
		if err := proto.Unmarshal(e.Msg, msg); err != nil {
			c.logger.Errorf("handle event proto.Unmarshal err: %v", err)
			c.cancel()
			return
		}
		switch msg.ID {
		case sc_pb.MessageID_MESSAGE_ID_ENTER_INSTANCE:
			m := &sc_pb.C2S_EnterInstance{}
			if err := proto.Unmarshal(msg.Payload, m); err != nil {
				c.logger.Errorf("handle event proto.Unmarshal err: %v", err)
				c.cancel()
				return
			}
			c.onEnter(m)
		case sc_pb.MessageID_MESSAGE_ID_ACTION:
			m := &sc_pb.C2S_Action{}
			if err := proto.Unmarshal(msg.Payload, m); err != nil {
				c.logger.Errorf("handle event proto.Unmarshal err: %v", err)
				c.cancel()
				return
			}
			c.onAction(m)
		}
	case *PongEvent:
		c.heartBeat = time.Now()
	}
}

func (c *Client) onEnter(msg *sc_pb.C2S_EnterInstance) {
	client, err := service.SceneNewClientLB()
	if err != nil {
		c.logger.Errorf("SceneNewClient err: %v", err)
		return
	}
	resp, err := client.Enter(c.ctx, &grpc_pb.EnterReq{
		USN:        c.USN,
		GatewaySID: GatewaySID,
		InstanceID: msg.InstanceID,
	})
	if err != nil {
		c.logger.Errorf("enter err: %v", err)
		return
	}
	c.SceneSID = resp.SceneSID
	c.UniqueNo = resp.UniqueNo
	c.InstanceID = msg.InstanceID
	c.WriteBytes(sc_pb.MessageID(resp.MessageID), resp.Payload)
}

func (c *Client) onLeave() {
	client, err := service.SceneNewClient(c.SceneSID)
	if err != nil {
		c.logger.Errorf("SceneNewClient err: %v", err)
		return
	}
	_, err = client.Leave(c.ctx, &grpc_pb.LeaveReq{
		USN:        c.USN,
		GatewaySID: GatewaySID,
		InstanceID: c.InstanceID,
		UniqueNo:   c.UniqueNo,
	})
	if err != nil {
		c.logger.Errorf("leave err: %v", err)
		return
	}
}

func (c *Client) onAction(msg *sc_pb.C2S_Action) {
	if c.SceneSID == 0 {
		return
	}
	if err := stream_client.SendMessageToScene(c.SceneSID, stream_client.FunAction, &grpc_pb.ActionReq{
		UniqueNo: c.UniqueNo,
		USN:      c.USN,
		Action:   int32(msg.Action),
		DirX:     msg.DirX,
		DirY:     msg.DirY,
		SkillID:  msg.SkillID,
	}); err != nil {
		c.logger.Errorf("send action err: %v", err)
	}
}
