package zigbee

import (
	"encoding/binary"

	"github.com/valyala/bytebufferpool"
)

type PackSendData struct {
	M1Flag uint16   //固定为F1F1
	M1Leng uint16   //包体1长度
	M1Cmd  uint8    //1字节
	Body1  SendData //n字节
	M1Crc  uint16   //整包CRC
}

func (o *PackSendData) EnCode() (*bytebufferpool.ByteBuffer, error) {
	bytebuf, err := o.Body1.EnCode()
	defer func() {
		if bytebuf != nil {
			bytebufferpool.Put(bytebuf)
		}
	}()
	if err != nil {
		return nil, err
	}
	buff := bytebufferpool.Get()
	buff.Write([]byte{0xF1, 0xF1}) //M1Flag uint16  //固定为F1F1
	tmp := make([]byte, 2)
	binary.BigEndian.PutUint16(tmp, uint16(bytebuf.Len()))
	buff.Write(tmp)             //M1Leng   uint16  //包体1长度
	buff.WriteByte(CmdSendData) //M1Cmd      uint8   //1字节
	buff.Write(bytebuf.B)
	crc16 := CRC16(buff.B)
	tmp2 := make([]byte, 2)
	binary.BigEndian.PutUint16(tmp2, crc16)
	buff.Write(tmp2) //计算内层CRC16
	return buff, nil
}
func (o *PackSendData) DeCode(Data []byte) error {
	if len(Data) < 7 {
		return ErrorProtocol
	}
	if Data[0] != 0xF1 || Data[1] != 0xF1 {
		return ErrorProtocol
	}
	o.M1Flag = 0xF1F1
	o.M1Leng = binary.BigEndian.Uint16(Data[2:4])
	o.M1Cmd = Data[4]
	o.M1Crc = binary.BigEndian.Uint16(Data[o.M1Leng+5 : o.M1Leng+7])
	//校验CRC1
	crc := CRC16(Data[0 : o.M1Leng+5])
	if o.M1Crc != crc {
		return ErrorInvalidCrc1
	}
	if o.M1Leng > 0 {
		return o.Body1.DeCode(Data[5 : o.M1Leng+5])
	}
	return ErrorProtocol
}

type SendData struct {
	Flag    uint8      //值为1
	Datalen uint16     //Header2的长度
	Data    MsgHeader2 //参见Header2
}

func (o *SendData) EnCode() (*bytebufferpool.ByteBuffer, error) {
	bytebuf, err := o.Data.EnCode() //Body2   Pack   //包体内容,普通功能协议或升级功能协议
	defer func() {
		if bytebuf != nil {
			bytebufferpool.Put(bytebuf)
		}
	}()
	if err != nil {
		return nil, err
	}
	buff := bytebufferpool.Get()
	buff.WriteByte(0x1) //Flag    uint8   //值为1
	tmp := make([]byte, 2)
	binary.BigEndian.PutUint16(tmp, uint16(bytebuf.Len()))
	buff.Write(tmp)       //Datalen uint16  //Header2的长度
	buff.Write(bytebuf.B) //MsgHeader2 MsgHeader2 //参见Header2
	return buff, nil
}

func (o *SendData) DeCode(Data []byte) error {
	if len(Data) > 3 {
		o.Flag = Data[0]
		o.Datalen = binary.BigEndian.Uint16(Data[1:3])
		return o.Data.DeCode(Data[3:])
	}
	return ErrorProtocol
}
