package com.hboxs.serialport.sbc.frame;

import android.util.Log;

import org.apache.commons.codec.binary.Hex;

/**
 * 命令帧
 */
public class VboxCommandFrame {

    /**
     * 开始字符
     */
    private final String stx = VboxCommand.STX;

    /**
     * 字节长度
     */
    private int length;

    /**
     * CMD指令
     */
    private String cmd;

    /**
     * data
     */
    private String data;


    /**
     * 结束字符
     */
    private final String etx = VboxCommand.ETX;


    public String getStx() {
        return stx;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getCmd() {
        return cmd;
    }

    public void setCmd(String cmd) {
        this.cmd = cmd;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getEtx() {
        return etx;
    }

    String result;

    /**
     * 读写M区
     *
     * @param cmd
     * @param data
     */
    public VboxCommandFrame(String cmd, String data) {
        this.cmd = cmd;

/*        String padHex = padHexTo16Custom(data).replace(" ", "");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(padHex);
        int sum = sumOfHexPairs(padHex);
        String hexString = intToHex4(sum);
        stringBuilder.append(hexString);
        Log.d("backinfo", "stringBuilder.toString():" + stringBuilder.toString());
        this.data = stringBuilder.toString();*/
         this.data =data;
    }


    public String intToHex4(int number) {
        return String.format("%04X", number); // 大写补零
        // 若需小写，改用 %04x
    }

    /**
     * 校验位
     */
    public int sumOfHexPairs(String hexStr) {
        int sum = 0;
        int len = hexStr.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException("输入字符串长度必须为偶数");
        }
        for (int i = 0; i < len; i += 2) {
            // 提取两位字符
            String pair = hexStr.substring(i, i + 2);
            // 转换为十进制数
            int value = Integer.parseInt(pair, 16);
            sum += value;
        }
        return sum;
    }

    /**
     * 10位字节数组，20个字符串
     */
    public String padHexTo16Custom(String hexStr) {
        int targetLength = 20;
        // 计算需补零的位数
        int zerosToAdd = targetLength - hexStr.length();
        if (zerosToAdd <= 0) {
            return hexStr; // 已满足或超过长度
        }
        // 后补零
        StringBuilder sb = new StringBuilder(hexStr);
        for (int i = 0; i < zerosToAdd; i++) {
            sb.append('0');
        }
        return sb.toString();
    }
}
