//
// Created by Ht on 2019/8/13.
//

#ifndef JSONPROTOCOL_JRPACKAGEVERIFER_H
#define JSONPROTOCOL_JRPACKAGEVERIFER_H


#include "JRDpBaseObj.h"
#include "JRPackage.h"
#include "JRDpCommandDecoder.h"

namespace jedp {

    static const char* sval_verify_action_xor = "xor";

    enum JRVerifyActionType {
        actionXorByte
    };

    class JE_API JRPackageVerifer :
            public JRDpBaseObj {

    public:
        explicit JRPackageVerifer(const std::string& verifyDef, const qlibc::QPObjectHolder<JRDpFieldDef>& fieldTable);
        ~JRPackageVerifer() override = default;


        /**
         *     解码前对缓存的数据合法性进行校验
         *
         * @param buff
         * @param bufflen
         * @return
         */
        bool verifyBuffer(const QByte *buff, size_t bufflen);


        /**
         *      解码后对package进行校验
         *
         * @param pPackage
         * @param buff
         * @param bufflen
         * @return
         */
        bool verifyPackage(JRPackage *pPackage, const QByte *buff, size_t bufflen);

        /**
         *      对正在生产的缓冲区数据生成校验码，并填充相关的缓存值
         *
         * @param fieldTable
         * @param buffMap
         * @param varFieldSizeMap
         */
        void verifyBuildingFieldBuffer(const qlibc::QPObjectHolder<JRDpFieldDef> &fieldTable,
                                       const std::unordered_map<std::string, QByte *> &buffMap,
                                       const std::unordered_map<std::string, size_t> &varFieldSizeMap);

        bool isValid() const {
            return mbValid;
        }

    protected:
        JRDpFieldDef* pVerifyField = nullptr;
        std::string mVerifyKey;
        std::vector<std::string> mVerifyFields;
        size_t mVerrifyLen = 1;
        JRVerifyActionType mVerifyAction = actionXorByte;
        bool mbValid = false;

        void appendFieldVerify(QByte *vrifyBuff, size_t vbufSize, QByte *fieldDataBuff, size_t fieldBuffSize);

        void setVerifyAction(std::string vaActionStr);
    };
}


#endif //JSONPROTOCOL_JRPACKAGEVERIFER_H
