package com.cisdi.data.AMETEKSurfaceVision.gateway;

import com.cisdi.data.AMETEKSurfaceVision.DynamicCodeActionParamDTO.PropertyConfig;
import com.cisdi.data.common.exception.BusinessException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 表检仪编码
 *
 * @author zhongda
 */
public class SurfaceVisionEncoder {

    /**
     * 下发命令编码
     * @param msgKey 消息头，也是平台电文ID
     * @param propsMap 下发消息
     * @param propertyConfigList 下发消息点位配置表
     * @param count 下发消息replayId
     */
    public static ByteBuf Encode(String msgKey, Map<String, Object> propsMap, List<PropertyConfig> propertyConfigList, int count) {
        StringBuffer stringBuffer = new StringBuffer();
        //组装消息头
        stringBuffer.append(msgKey).append(SurfaceVisionConstants.SEPARATE);
        //非Query命令添加replayId
        if (!msgKey.startsWith(SurfaceVisionConstants.QUERY)){
            stringBuffer.append(count).append(SurfaceVisionConstants.SEPARATE);
        }
        //组装消息体
        for (PropertyConfig propertyConfig : propertyConfigList){
            String key = propertyConfig.getPropertyId();
            stringBuffer.append(propsMap.get(key))
                .append(SurfaceVisionConstants.SEPARATE);
        }
        //组装消息结尾
        stringBuffer.append(String.valueOf(SurfaceVisionConstants.END));

        //UTF_8编码下发消息
        byte[] bytes = stringBuffer.toString().getBytes(StandardCharsets.UTF_8);
        ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bytes);

        return wrappedBuffer;
    }

}
