package main

import (
	"../nnet"
	"../nt"
	"errors"
)

var (
	ErrRecvedDataLength = errors.New("Received size of data if not sufficient.")
	ErrRecvedOutOfBound = errors.New("Data received is too long") //TODO 可能不是错误，而是缓冲区太小，后期调整
)

type KgPacket struct {
	msg    []byte
	flag   int32 // 是否关闭. 0 不关闭
	reason int32 // 关闭时的关闭原因
}

func NewKgPacket(data []byte, params ...int32) *KgPacket {
	var flag int32 = 0
	var reason int32 = 0
	if len(params) > 0 {
		flag = params[0]
	}
	if len(params) > 1 {
		reason = params[1]
	}
	return &KgPacket{
		msg:    data,
		flag:   flag,
		reason: reason,
	}
}

func (self *KgPacket) Serialize() []byte {
	return self.msg
}

func (self *KgPacket) Destroy(b []byte) {
}

func (self *KgPacket) ShouldClose() (bool, int32) {
	return self.flag != 0, self.reason
}

type KgProtocol struct {
}

// 这里产生的 Packet 在 OnMessage 结束后释放
func (self *KgProtocol) ReadPacket(conn nnet.IConn) (nnet.IPacket, error) {
	buf := make([]byte, nt.DEF_MAX_NET_BUFFER)

	n, err := conn.Read(buf)
	if err != nil {
		//utils.DefBufPool.Put(buf)
		return nil, err
	}
	return NewKgPacket(buf[:n]), nil
}
