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

import com.its.vds.dto.TbVdsCtlrDto;
import com.its.vds.xnettcp.vds.protocol.VdsFramePacket;
import com.its.vds.xnettcp.vds.protocol.VdsReqFramePacket;
import com.its.vds.xnettcp.vds.protocol.enums.eVdsOpCode;
import com.its.vds.xnettcp.vds.protocol.impl.andong.VdsAndongFramePacket;
import lombok.extern.slf4j.Slf4j;

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

/**
 * VDS Check Sequence 요청
 */
@Slf4j
public class VdsReqCheckSequence extends VdsReqFramePacket {

    private final VdsFramePacket framePacket;

    public VdsReqCheckSequence(TbVdsCtlrDto vdsObj, short[] formId, byte[] dispSec) {
        this.opCode = eVdsOpCode.OP_VDS_CHECK_SEQUENCE;
        this.packetNmbr = (short)this.opCode.getValue();
        byte opCode = (byte)this.opCode.getValue();
        this.packetNmbr = vdsObj.getSeqNext();
        this.framePacket = new VdsAndongFramePacket(vdsObj.getGroupNo().intValue(), vdsObj.getVdsCtlrNmbr().intValue(), this.packetNmbr, opCode);

        makeBody(formId, dispSec);
    }

    public void makeBody(short[] formId, byte[] dispSec) {
        int bodySize = (2 * formId.length) + (dispSec.length);
        ByteBuffer byteBuffer = ByteBuffer.allocate(bodySize);
        byteBuffer.order(ByteOrder.BIG_ENDIAN);

        for (int ii = 0; ii < formId.length; ii++) {
            byteBuffer.putShort((short)(formId[ii] & 0xFFFF));    // 폼 ID
            byteBuffer.put((byte)(dispSec[ii] & 0xFF));           // 폼 표출시간
        }

        this.framePacket.setBody(byteBuffer.array());
    }

    @Override
    public ByteBuffer getByteBuffer() {
        return this.framePacket.getByteBuffer();
    }

}
