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

import com.its.app.utils.SysUtils;
import com.its.vds.dto.TbVdsCtlrDto;
import com.its.vds.xnettcp.vds.process.response.VdsResponse;
import com.its.vds.xnettcp.vds.protocol.VdsFramePacket;
import com.its.vds.xnettcp.vds.protocol.enums.eVdsOpCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
@RequiredArgsConstructor
public class VdsResCheckMemory implements VdsResponse {

    private final TbVdsCtlrDto vdsObj;
    private final VdsFramePacket resFramePacket;
    private byte dataFileCode;
    private String dataFileName;
    private int dataFileSize;

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

        ByteBuffer byteBuffer = ByteBuffer.wrap(body);
        byteBuffer.order(ByteOrder.BIG_ENDIAN);
        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. VDS %d", eVdsOpCode.OP_VDS_DATA_SPEED, this.vdsObj.getVdsCtlrNmbr()));
        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();
    }

}
