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.VdsProtocolConst;
import com.its.vds.xnettcp.vds.protocol.enums.eVdsDetectErrorCode;
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 VdsResSetTemperature implements VdsResponse {

    private final TbVdsCtlrDto vdsObj;
    private final VdsFramePacket resFramePacket;
    private boolean success;
    private eVdsDetectErrorCode error;
    private String content;

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

        byte result = body[0];
        if (result == VdsProtocolConst.VDS_ACK) {
            parsing(ByteBuffer.wrap(body, 1, body.length - 1));
        }
        else if (result == VdsProtocolConst.VDS_ACK) {
            this.success = false;
            this.error = eVdsDetectErrorCode.getValue(result & 0xFF);
            if (this.error == null) {
                log.error("VdsResSetTemperature.process: VDS {}, Unknown error code: {}.", this.vdsObj.getVdsCtlrNmbr(), String.format("0x%02X", result & 0xFF));
//                this.error = eVdsDetectErrorCode.ERROR_UNKNOWN;
            }
            this.content = "NONE";
        }
        else {
            parsing(ByteBuffer.wrap(body));
        }

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

        return true;
    }

    private void parsing(ByteBuffer byteBuffer) {
        this.success = true;
        this.error = eVdsDetectErrorCode.DETECT_ERROR_NONE;
        this.content = "";
        StringBuilder data = new StringBuilder();
        byteBuffer.order(ByteOrder.BIG_ENDIAN);
    }

    public String toString() {
        StringBuilder data = new StringBuilder();
        data.append(String.format("RESPONSE-%s. VDS %d", eVdsOpCode.OP_VDS_STATUS_INITIALIZE, this.vdsObj.getVdsCtlrNmbr()));
        data.append(System.getProperty("line.separator"));
        data.append(String.format("Upload Current Display Form: %s, NAK: %s", this.success, this.error));
        data.append(System.getProperty("line.separator"));
        data.append("CONTENT:");
        data.append(System.getProperty("line.separator"));
        data.append(this.content);
        return data.toString();
    }

}
