package ws_handler

import (
	"common/proto/sc/sc_pb"
	"google.golang.org/protobuf/proto"
)

// WriteMessage 向客户端发送消息
func (c *Client) WriteMessage(id sc_pb.MessageID, data proto.Message) {
	if c.conn == nil || c.conn.IsClose() {
		return
	}
	d, err := proto.Marshal(data)
	if err != nil {
		c.logger.Errorf("WriteMessage proto.Marshal err: %v", err)
		return
	}
	m, err := proto.Marshal(&sc_pb.Message{
		ID:      id,
		Payload: d,
	})
	if err != nil {
		c.logger.Errorf("WriteMessage proto.Marshal err: %v", err)
		return
	}
	if err = c.conn.Write(m); err != nil {
		c.logger.Errorf("WriteMessage err: %v", err)
	}
}

// WriteBytes 向客户端发送字节数据
func (c *Client) WriteBytes(id sc_pb.MessageID, data []byte) {
	if c.conn == nil || c.conn.IsClose() {
		return
	}
	m, err := proto.Marshal(&sc_pb.Message{
		ID:      id,
		Payload: data,
	})
	if err != nil {
		c.logger.Errorf("WriteBytes proto.Marshal err: %v", err)
		return
	}
	if err = c.conn.Write(m); err != nil {
		c.logger.Errorf("WriteBytes err: %v", err)
	}
}

// WriteBytesPreMarshal 向客户端发送字节数据（需要预先打包，适合广播相同数据）
func (c *Client) WriteBytesPreMarshal(data []byte) {
	if c.conn == nil || c.conn.IsClose() {
		return
	}
	if err := c.conn.Write(data); err != nil {
		c.logger.Errorf("WriteBytes err: %v", err)
	}
}
