package com.its.vms.xnettcp.vms.process.response.impl;

import com.its.app.utils.SysUtils;
import com.its.vms.dto.TbVmsCtlrDto;
import com.its.vms.xnettcp.vms.process.response.VmsResponse;
import com.its.vms.xnettcp.vms.protocol.VmsFramePacket;
import com.its.vms.xnettcp.vms.protocol.enums.eVmsOpCode;
import com.its.vms.xnettcp.vms.protocol.impl.dle.VmsDleFramePacket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;

@Slf4j
@RequiredArgsConstructor
public class VmsResDataUpload implements VmsResponse {

    private final TbVmsCtlrDto vmsObj;
    private final VmsFramePacket resFramePacket;
    private byte dataFileCode;
    private String dataFileName;
    private int dataFileSize;

    @Override
    public boolean process() {
        /**
         * ACK/NAK 확인
         */
        byte[] body = this.resFramePacket.getBody();
        log.info("VmsResDataUpload.process: VMS {}, body length: {}.", this.vmsObj.getVmsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 6) {
            log.error("VmsResDataUpload.process: VMS {}, body length error: {}.", this.vmsObj.getVmsCtlrNmbr(), body != null ? body.length : 0);
            return false;
        }

        ByteBuffer byteBuffer = ByteBuffer.wrap(body);
        byteBuffer.order(VmsDleFramePacket.BYTE_ORDER);
        this.dataFileCode = byteBuffer.get();
        int fileNameSize = (int)(byteBuffer.get() & 0xFF);
        this.dataFileSize = byteBuffer.getInt();
        if (fileNameSize > 0) {
            byte[] name = new byte[fileNameSize];
            byteBuffer.get(name);
            this.dataFileName = SysUtils.byteArrayToString(name);
        }
        else {
            this.dataFileName = "UNKNOWN";
        }
        if (this.dataFileSize > 0) {
            byte[] dataFile = new byte[this.dataFileSize];
            byteBuffer.get(dataFile);
        }
        else {
            this.dataFileSize = 0;
        }

        log.info("{}", toString());

        return true;
    }

    public String toString() {
        StringBuilder data = new StringBuilder();
        data.append(String.format("RESPONSE-%s. VMS %d", eVmsOpCode.OP_VMS_DATA_UPLOAD, this.vmsObj.getVmsCtlrNmbr()));
        data.append(System.getProperty("line.separator"));
        data.append(String.format("Data File Location: 0x%02X, Name: %s, Size: %d", this.dataFileCode, this.dataFileName, this.dataFileSize));
        return data.toString();
    }

}
