package com.its.pis.xnettcp.vds.protocol;

import com.its.pis.entity.TbVdsCtlr;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

@Slf4j
@Getter
public class VdsResFramePacket {

    private ByteOrder byteOrder = VdsProtocol.byteOrder;

    TbVdsCtlr       vdsObj;
    VdsResFrameHead head;
    byte[]          body;
    VdsResFrameTail tail;

    public VdsResFramePacket(TbVdsCtlr obj, byte[] packet, int size) {
        this.vdsObj = obj;
        if (packet != null) {
            // HEAD
            this.head = new VdsResFrameHead(packet);

            // BODY
            int bodyLength = size - VdsResFrameHead.SIZE - VdsResFrameTail.SIZE;
            log.info("FrameSize: {}, BodyLength: {}", size, bodyLength);
            if (bodyLength > 0) {
                this.body = new byte[bodyLength];
                System.arraycopy(packet, VdsResFrameHead.SIZE, this.body, 0, bodyLength);
            }

            // TAIL
            this.tail = new VdsResFrameTail(packet, VdsResFrameHead.SIZE + bodyLength);
        }
        else {
            log.error("VdsResFramePacket: create failed, packet error");
        }
    }

    public String getObjectInfo() {
        if (this.vdsObj != null) {
            return this.vdsObj.getVDS_CTLR_ID();
        }
        return "???";
    }
    public byte getOpCode() {
        if (this.head != null) {
            return this.head.getOpCode();
        }
        return VdsProtocol.vds_Unknown;
    }
    public void setByteOrder(ByteOrder byteOrder) {
        this.byteOrder = byteOrder;
    }

    /**
     * 요청 패킷을 ByteBuffer 로 변경하여 리턴
     * @return
     */
    public ByteBuffer getByteBuffer() {
        int bodySize = 0;
        if (this.body != null) {
            bodySize = this.body.length;
        }
        ByteBuffer byteBuffer = ByteBuffer.allocate(VdsResFrameHead.SIZE + bodySize + VdsResFrameTail.SIZE);
        byteBuffer.order(this.byteOrder);

        // HEAD
        byteBuffer.put(this.head.getDle());
        byteBuffer.put(this.head.getStx());
        byteBuffer.putShort(this.head.getGroupNo());
        byteBuffer.putShort(this.head.getControllerNo());
        byteBuffer.put(this.head.getOpCode());
        byteBuffer.put(this.head.getStatus1());
        byteBuffer.put(this.head.getStatus2());

        // BODY
        if (bodySize > 0) {
            byteBuffer.put(this.body);
        }

        // TAIL
        byteBuffer.put(this.tail.getDle());
        byteBuffer.put(this.tail.getEtx());
        byteBuffer.putShort(this.tail.getCrc());

        return byteBuffer;
    }

}
