package com.hboxs.serialport.frame;

import com.hboxs.serialport.Command;
import com.hboxs.serialport.util.ChecksumUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 响应帧
 */
public class ResponseFrame {
    /**
     * 开始字符
     */
    private byte stx = Command.STX;
    /**
     * 数据
     */
    private byte[] data;
    /**
     * 结束字符
     */
    private byte etx = Command.ETX;
    /**
     * 校验和
     */
    private byte[] sum;
    /**
     * 原始校验和
     */
    private byte[] oriSum;

    /**
     * 帧数据
     */
    private byte[] frameData;

    /**
     * 是否通过校验
     */
    private boolean validSum;

    public byte getStx() {
        return stx;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
        checksum();
    }

    public byte getEtx() {
        return etx;
    }

    public byte[] getSum() {
        return sum;
    }

    public byte[] getOriSum() {
        return oriSum;
    }

    public void setOriSum(byte[] oriSum) {
        this.oriSum = oriSum;
    }

    public byte[] getFrameData() {
        return frameData;
    }

    public boolean isValidSum() {
        return validSum;
    }

    private List<Byte> getChecksumData() {
        List<Byte> byteList = new ArrayList<>();
        if (data != null) {
            for (byte b : data) {
                byteList.add(b);
            }
        }
        byteList.add(etx);
        return byteList;
    }

    /**
     * 计算校验和
     */
    private void checksum() {
        List<Byte> checksumData = getChecksumData();
        this.sum = ChecksumUtils.calculate(checksumData);

        frameData = new byte[checksumData.size() + 3];
        frameData[0] = stx;
        for (int i = 0; i < checksumData.size(); i++) {
            frameData[i + 1] = checksumData.get(i);
        }
        if (oriSum != null && oriSum.length == 2) {
            this.validSum = (oriSum[0] == sum[0] && oriSum[1] == sum[1]);
            frameData[checksumData.size() + 1] = oriSum[0];
            frameData[checksumData.size() + 2] = oriSum[1];
        } else {
            this.validSum = false;
        }
    }
}
