package com.gyee.protocol.gyfp2.message;

import com.gyee.edge.common.utils.BytesUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * @author ：
 * @date ：Created in 2022/8/25 17:34
 * @description：  定义gyfp2协议实体类
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GYMessage implements Serializable {
    private byte[] header=new byte[]{'G','Y','F','P','V','2','0','0'};
    private short length;
    private short count;
    private int attribute;
    private List<MessageData> messageDataList;
    private MessageMutable messageMutable;



     public byte[] toBytes(){
          /*不指定默认256，指定64以内默认大小都是64.
         如果写入后数据大小未超过512个字节，则选择下一个16的整数倍进行扩容。比如写入数据后大小为12，则扩容后的capacity是16。
         如果写入后数据大小超过512个字节，则选择下一个2n。比如写入后大小是512字节，则扩容后的capacity是210=1024。(因为29=512，长度已经不够了)
         扩容不能超过max capacity，否则会报错*/
         int sum = 0;
         ByteBuf buffer = Unpooled.buffer(10);
         buffer.writeBytes(getHeader());
         //占住总长度字节大小，方便后续代替
         buffer.writeShort(1);
         //占住数据项个数大小，方便后续代替
         buffer.writeShort(1);
         buffer.writeInt(getAttribute());
         if (getAttribute() > 0){
             buffer.writeBytes(getMessageMutable().toBytes(getAttribute()));
         }
         for (MessageData messageData : getMessageDataList()){
             byte[] bytes = messageData.toBytes(getAttribute(),getMessageMutable().getMessageType());
             sum++;
             buffer.writeBytes(bytes);
         }
         //替换长度和数据项字节码
         ByteBufUtil.setShortBE(buffer,getHeader().length,ByteBufUtil.getBytes(buffer).length);
         ByteBufUtil.setShortBE(buffer,getHeader().length+2,sum);
         return ByteBufUtil.getBytes(buffer);
     }

     //字节数组转对象
     public static GYMessage toObject(byte[] bytes){
         GYMessage gyMessage = new GYMessage();
         if (bytes.length>0){
             gyMessage.setLength(BytesUtils.getShort(bytes,8));
             gyMessage.setCount(BytesUtils.getShort(bytes,10));
             gyMessage.setAttribute(BytesUtils.getInt(bytes,12));
             gyMessage.setMessageMutable(MessageMutable.toMessageMutable(bytes,BytesUtils.getInt(bytes,12)));
             gyMessage.setMessageDataList(MessageData.toMessageData(bytes,BytesUtils.getInt(bytes,12)));
         }
         return gyMessage;
     }

}
