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

    private final TbVdsCtlrDto vdsObj;
    private final VdsFramePacket resFramePacket;
    private int scheduleCount;
    private String schedule;

    @Override
    public boolean process() {

        byte[] body = this.resFramePacket.getBody();
        log.info("VdsResStatusValidation.process: VDS {}, body length: {}.", this.vdsObj.getVdsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 30) {
            log.error("VdsResStatusValidation.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);

        StringBuilder data = new StringBuilder();
        this.scheduleCount = body.length / 3;
        for (int ii = 0; ii < this.scheduleCount; ii++) {
            short formId = byteBuffer.getShort();
            byte dispTm = byteBuffer.get();
            data.append(System.getProperty("line.separator"));
            data.append(String.format("%2d 폼: ID %d, Display Second %d", ii + 1, formId, dispTm & 0x0FF));
        }
        this.schedule = data.toString();

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

        return true;
    }

    public String toString() {
        StringBuilder data = new StringBuilder();
        data.append(String.format("RESPONSE-%s. VDS %d", eVdsOpCode.OP_VDS_PARAM_UPLOADING, this.vdsObj.getVdsCtlrNmbr()));
        data.append(System.getProperty("line.separator"));
        data.append(String.format("Schedule %d EA.", this.scheduleCount));
        data.append(this.schedule);
        return data.toString();
    }

}
