package com.its.vms.xnettcp.vms.protocol.impl.dle;

import com.google.common.primitives.Bytes;
import com.its.vms.xnettcp.vms.protocol.VmsFrameTail;
import com.its.vms.xnettcp.vms.protocol.VmsProtocolConst;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Data
public class VmsDleFrameTail implements VmsFrameTail {

    public static final int TAIL_SIZE = 4;
    private int opCodePos = 4;

    private byte dle = VmsProtocolConst.VMS_DLE;
    private byte etx = VmsProtocolConst.VMS_ETX;
    private short crc;

    public VmsDleFrameTail() {
        this.crc = 0;
    }

    public VmsDleFrameTail(byte[] packet) {
        if (packet != null && packet.length >= TAIL_SIZE) {
            ByteBuffer byteBuffer = ByteBuffer.wrap(packet);
            byteBuffer.order(VmsDleFramePacket.BYTE_ORDER);
            this.dle = byteBuffer.get(packet.length-4);
            this.etx = byteBuffer.get(packet.length-3);
            this.crc = (short)(byteBuffer.getShort(packet.length-2) & 0xFFFF);
        }
        else {
            log.error("VmsReqDleFrameHead: create failed, headBytes error");
        }
    }

    public byte[] getBuffer() {
        List<Byte> list = new ArrayList<Byte>();

        // TAIL
        list.add(this.dle);
        list.add(this.etx);
        list.add((byte)(this.crc & 0xFF00 >> 8));
        list.add((byte)(this.crc & 0x00FF     ));

        return Bytes.toArray(list);
    }
}
