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.eVmsFileSaveLocation;
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;

/**
 * Data Upload 요청
 */
@Slf4j
public class VmsReqDataUpload extends VmsReqFramePacket {

    private final VmsFramePacket framePacket;

    public VmsReqDataUpload(TbVmsCtlrDto vmsObj, eVmsFileSaveLocation saveLoc, String fileName) {
        this.opCode = eVmsOpCode.OP_VMS_DATA_UPLOAD;
        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(saveLoc, fileName);
    }

    public void makeBody(eVmsFileSaveLocation saveLoc, String fileName) {
//        Download Data 저장 위치 Code   1
//        파일명 길이                    1
//        기타                           1
//        저장할 파일명                  n
        int fileNameSize = fileName.length();
        int bodySize = 3 + fileNameSize;
        //log.info("VmsReqDataUpload.makeBody: bodySize {}", bodySize);
        ByteBuffer byteBuffer = ByteBuffer.allocate(bodySize);
        byteBuffer.order(ByteOrder.BIG_ENDIAN);

        byteBuffer.put((byte)(saveLoc.getValue() & 0xFF));
        byteBuffer.put((byte)(fileNameSize & 0xFF));
        byteBuffer.put((byte)0x00);
        byteBuffer.put(fileName.getBytes());

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

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

}
