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

import com.its.vms.dto.TbVmsCtlrDto;
import com.its.vms.xnettcp.vms.protocol.VmsFramePacket;
import com.its.vms.xnettcp.vms.protocol.VmsReqFramePacket;
import com.its.vms.xnettcp.vms.protocol.enums.eVmsOpCode;
import com.its.vms.xnettcp.vms.protocol.enums.eVmsProtocolVersion;
import com.its.vms.xnettcp.vms.protocol.impl.dle.VmsDleFramePacket;
import com.its.vms.xnettcp.vms.protocol.impl.std.VmsStdFramePacket;
import lombok.extern.slf4j.Slf4j;

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

/**
 * Download Form Schedule 요청
 */
@Slf4j
public class VmsReqDownloadFormSchedule extends VmsReqFramePacket {

    private final VmsFramePacket framePacket;

    public VmsReqDownloadFormSchedule(TbVmsCtlrDto vmsObj, short[] formId, byte[] dispSec) {
        this.opCode = eVmsOpCode.OP_VMS_DOWNLOAD_FORM_SCHEDULE;
        this.packetNmbr = (short)this.opCode.getValue();
        byte opCode = (byte)this.opCode.getValue();
        if (vmsObj.getProtocolVer() == eVmsProtocolVersion.PROTOCOL_ANDONG.getValue()) {
            this.packetNmbr = vmsObj.getSeqNext();
            this.framePacket = new VmsStdFramePacket(vmsObj.getGroupNo().intValue(), vmsObj.getVmsCtlrNmbr().intValue(), this.packetNmbr, opCode);
        }
        else if (vmsObj.getProtocolVer() == eVmsProtocolVersion.PROTOCOL_EX_FIGURE.getValue()) {
            this.framePacket = new VmsDleFramePacket(vmsObj.getGroupNo().intValue(), vmsObj.getCtlrLocalNo(), opCode);
        }
        else {
            this.framePacket = new VmsDleFramePacket(vmsObj.getGroupNo().intValue(), vmsObj.getCtlrLocalNo(), opCode);
        }

        makeBody(formId, dispSec);
    }

    public void makeBody(short[] formId, byte[] dispSec) {
        int bodySize = (2 * formId.length) + (dispSec.length);
        //log.info("VmsReqDownloadFormSchedule.makeBody: bodySize {}", bodySize);
        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();
    }

}
