import 'package:buffer/buffer.dart';
import 'dart:typed_data';

class MsgPacketModule {
  int comId;
  int msgId;

  List<int> msg;

  MsgPacketModule({this.comId, this.msgId, this.msg});
}

class MsgPacketUtil {
  static Uint8List encode(MsgPacketModule msgModule) {
    int msgLen = msgModule.msg.length;
    msgLen += 9; //修改为整体长度

    var buffWriter = ByteDataWriter(bufferLength: msgLen, endian: Endian.big);

    buffWriter.writeInt16(msgModule.comId);
    buffWriter.writeInt16(msgModule.msgId);
    buffWriter.writeInt8(0x24);

    buffWriter.writeUint32(msgLen);

    buffWriter.write(msgModule.msg);

    return buffWriter.toBytes();
  }

  static decode(Uint8List msg) {
    var decodeMsg = new MsgPacketModule();
    var buffReader = ByteDataReader(endian: Endian.big);
    buffReader.add(msg);

    int cmdId = buffReader.readInt16();
    decodeMsg.comId = cmdId;

    int msgId = buffReader.readInt16();
    decodeMsg.msgId = msgId;

    buffReader.readInt8();
    
    int msgLen = buffReader.readUint32();

    if (msgLen > 9) {
      decodeMsg.msg = buffReader.read(msgLen - 9);
    }

    return decodeMsg;
  }
}
