package zigbee

import (
	"encoding/binary"

	"github.com/valyala/bytebufferpool"
)

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

func (o *PackSetPid) SetData(pid uint16, freq byte) {
	o.Body1.PID = pid
	o.Body1.Frequency = freq
}

func (o *PackSetPid) 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(CmdSetPid) //M1Cmd      uint8   //1字节
	buff.Write(bytebuf.B)     //包体1

	//crc1
	crc16 := CRC16(buff.B)
	tmp2 := make([]byte, 2)
	binary.BigEndian.PutUint16(tmp2, crc16)
	buff.Write(tmp2) //外层CRC16
	return buff, nil
}

func (o *PackSetPid) DeCode(Data []byte) error {
	if len(Data) < 7 {
		return ErrorProtocol
	}
	if Data[0] != 0xF1 || Data[1] != 0xF1 {
		return ErrorProtocol
	}
	o.M1Flag = binary.BigEndian.Uint16(Data[0:2])
	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 PidFreq struct {
	PID       uint16
	Frequency byte
}

func (o *PidFreq) EnCode() (*bytebufferpool.ByteBuffer, error) {
	buff := bytebufferpool.Get()
	tmp := make([]byte, 2)
	binary.BigEndian.PutUint16(tmp, o.PID)
	buff.Write(tmp)
	buff.WriteByte(o.Frequency)
	return buff, nil
}
func (o *PidFreq) DeCode(Data []byte) error {
	if len(Data) >= 3 {
		o.PID = binary.BigEndian.Uint16(Data)
		o.Frequency = Data[2]
		return nil
	}
	return ErrorProtocol
}
