#ifndef QFMCLIENT_H
#define QFMCLIENT_H

#include <QThread>
#include <windows.h>
#include <QTextStream>
#include <QCoreApplication>

#define MAX_CODE_KEY            32
#define MAX_CTRL_INFO_LEN       16
#define MAX_BUF_LEN             4096
#define MAX_REQ_COUNT           25600
#define ROLL_BACK_FILE_NAME     "fmclient.rbk"

class QFmClient : public QThread
{    
    Q_OBJECT
public:
    QFmClient(QObject *parent = NULL);

    void run();


    bool Init(QString proxy_IP, unsigned short proxy_port, unsigned short listen_prot, unsigned short long_timeout, unsigned short short_timeout);
signals:

    void Error(QString error);

private:
    void CloseSocket(int *sock);
    void GetKey();
    bool StartListenport();
    void CheckRollBackData();
    int Try2ConnectZhProxy();
    int SendCtrlInfo2Proxy();
    void WaitAndSleep(int elapse);
    bool WaitForConnectReqFromPos();
    int ProcessPosReqData(QJsonObject& object);
    void AddReqCount(QJsonObject &object);
    int CheckIsCompleteJsonData(int *count, char *data);
    int RecvSockData(int sock, char *buffer, int length);
    int WaitAndReadDataFromPos(int type, int flag);
    char *DecodeRecvData(char *buf, int length, int *dLength);
    int UTF8ToGBK(unsigned char *lpUTF8Str, unsigned char *lpGBKStr, int nGBKStrLen);
    int GBKToUTF8(unsigned char *lpGBKStr, int gbkLen, unsigned char *lpUTF8Str, int nUTF8StrLen);
    int CheckReqFromPos(char *pJsonData, int dLength, int chkValue);
    int SendSocketData(int sock, char *buf, int length, int flag);
    char *EncodeSendData(char *buf, int length, int *eLength);
    int SendData2ZhProxyAndWaitRspData();
    int RecvAndCheckDataFromSock(int sock, int flag, int type);
    int ProcessZhProxyRspDataAndSend2Pos();
    int CheckRecvedData();
    void BackupPosReq(char *req);
private:

    bool _endflag;

    char _recvbuf[MAX_BUF_LEN];
    char _tempbuf[MAX_BUF_LEN];
    char _sendbuf[MAX_BUF_LEN];

    char _codeBuf[MAX_BUF_LEN];

    unsigned char _codeKey[MAX_CODE_KEY];

    //proxy IP
    char _proxyIP[30];
    //proxy 端口
    unsigned short _proxyPort;

    //QFMClient监听端口
    unsigned short _clientPort;

    //应用层分段大小(1024)
    unsigned int _fmMSS;
    //监听本地端口的socket
    int _listenSock;
    //接收pos请求的socket
    int _acceptedSock;
    //和proxy交互的socket
    int _zhProxySock;

    //接收数据长度
    int _rcvLength;

    //长超时
    unsigned short _longTimeOut;
    //短超时
    unsigned short _shortTimeOut;
    //当前使用超时
    unsigned short _sockTimeOut;

    char  _keyLength;
    char  _curKeyPos;
    char  _codeFlag;
    char  _reserved;



    static unsigned int s_reqCount;
};

#endif // QFMCLIENT_H
