#ifndef PQ_MSGHEADER_H
#define PQ_MSGHEADER_H

#include <QObject>
#include <QtEndian>
namespace PQ {


/***
 * 处理tcp分包的包头
*/
struct  MSGHeader
{
    MSGHeader():msgID(0),msgType(0),length(0),compress(0x00),encrypt(0x00)
    {}
    uint msgID;
    ushort msgType;
    uint length;
    uchar compress;
    uchar encrypt;

    QByteArray buildArray()
    {
        QByteArray buffer;
        buffer.append("PQ");
        char buf[4];
        qToBigEndian(msgID,reinterpret_cast<uchar *>(&buf[0]));
        buffer.append(&buf[0],4);
        qToBigEndian(msgType,reinterpret_cast<uchar *>(&buf[0]));
        buffer.append(&buf[0],2);
        qToBigEndian(length,reinterpret_cast<uchar *>(&buf[0]));
        buffer.append(&buf[0],4);
        buffer.append(compress);
        buffer.append(encrypt);

        buffer.append('p');
        buffer.append('q');
        return buffer;

    }
};


class  MSGRead :public QObject
{
    Q_OBJECT
public:
    MSGRead(bool errorContine = true, QObject * parent = 0);
    ~MSGRead(){}

    bool readMsg(const QByteArray data);
signals:
    void revicedMSG(const MSGHeader & header, QByteArray body);
    void hasError();

private:
    bool readHeaderCloum(char byte, int max){
        byteBuffer[_bytePos] = byte;
        _bytePos ++;
        return (_bytePos >= max);
    }
    bool readData(const QByteArray & data,int & pos, int max);
private:
    bool _errorContine;
    int _status;
    int _bytePos;
    int _needBytes;
    char byteBuffer[4];
    MSGHeader header;
    QByteArray body;
};

}

#endif // MSGHEADER_H
