#ifndef NETWORKPROTOCOL_H
#define NETWORKPROTOCOL_H

#define USE_BYTEARRAY_IN_SEND

#include "GlobalDefine.h"
#include "ProtocolDefs.h"
#include "AbstractNetworkInterface.h"
#include <QByteArray>

class CNetworkProtocol
{
public:
    CNetworkProtocol();
    ~CNetworkProtocol();
    QByteArray GetTxPacket(unsigned char MessageID, unsigned char Flags, const char *Data, int Size, unsigned char Address, unsigned char ID, unsigned char SenderDevice = ID_SMS_CLIENT, unsigned char SenderAddress = 1);
    int AnalyzeRxBuffer(QByteArray Buffer);
    void PrepareForNewPacket();
    void SetManualPacketReset(bool Manual);

    virtual int NewFrameReceived(int TargetDeviceID, int TargetDeviceAddress, int SenderID, int SenderAddress, int MessageID, int DataSize, QByteArray Data) = 0;

    enum ProtocolRetValues
    {
        PROTOCOL_RET_OK_PACKET_COMPLETE,
        PROTOCOL_RET_OK_PACKET_INCOMPLETE,
        PROTOCOL_RET_OK_BAD_HEADER,
        PROTOCOL_RET_ERROR_INVALID_TARGET_DEVICE,
        PROTOCOL_RET_ERROR_INVALID_TARGET_ADDRESS,
        PROTOCOL_RET_ERROR_BAD_CRC,
        PROTOCOL_RET_ERROR_SM_LOGIC,
        PROTOCOL_RET_ERROR_EMPTY_BUFFER
    };

    char ProtocolGetSenderID(){return SenderID;}
    char ProtocolGetSenderAddress(){return SenderAddress;}
    int ProtocolGetCmd(){return RxCmd;}
    int ProtocolGetDataSize(){return RxSize;}
    QByteArray ProtocolGetData(){return mDataBuffer;}


private:
    void ResetRxStateMachine();
    unsigned char CalcCRC(char *Buffer, int Size);
 //   int TxData(unsigned char MessageID,unsigned char Flags,unsigned char *Data,int Size, unsigned char Address,unsigned char ID);

    int RxStateMachine(unsigned char Data);

    //State Machine states
    enum States
    {
        Initialization,
        RxHeader,
        RxID,
        RxAdd,
        RxMyID,
        RxMyAddress,
        RxFlags,
        RxCMD,
        RxSize1,
        RxSize2,
        RxSize3,
        RxSize4,
        RxData,
        RxCRC
    };

    bool mIsResetManual;


    char *RxBuff;
    char  mRxData[MAX_MESSAGE_SIZE+10];

    int RxState;
    int RxSize;
    char SenderID;
    char SenderAddress;
    int RxCmd;
    int TargetDeviceID;
    int TargetAddress;
    int DataCnt;
    int BufPtr;
    unsigned char CRC;
    unsigned char Flags;

    unsigned char State;

    QByteArray mDataBuffer;

};

#endif // NETWORKPROTOCOL_H
