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

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 VdsResDataSpeed implements VdsResponse {

    private final TbVdsCtlrDto vdsObj;
    private final VdsFramePacket resFramePacket;
    private int[] categorySped;

    @Override
    public boolean process() {
        // VDS 카타고리별 속도 데이터
        byte[] body = this.resFramePacket.getBody();
        log.info("VdsResDataSpeed.process: VDS {}, body length: {}.", this.vdsObj.getVdsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 2+24) {
            log.error("VdsResDataSpeed.process: VDS {}, body length error: {}.", this.vdsObj.getVdsCtlrNmbr(), body != null ? body.length : 0);
            return false;
        }

        this.categorySped = new int[12];
        ByteBuffer byteBuffer = ByteBuffer.wrap(body);
        byteBuffer.order(ByteOrder.BIG_ENDIAN);

        for (int ii = 0; ii < 12; ii++) {
            this.categorySped[ii] = byteBuffer.getShort();
        }

        if (this.vdsObj.getDebug().isDebug()) {
            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"));
        for (int ii = 0; ii < 12; ii++) {
            data.append(String.format(", %d", this.categorySped[ii]));
        }
        return data.toString();
    }

}
