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

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.eVmsErrorCode;
import com.its.vms.xnettcp.vms.protocol.enums.eVmsOpCode;
import com.its.vms.xnettcp.vms.protocol.impl.dle.VmsDleFramePacket;
import com.its.vms.xnettcp.vms.protocol.VmsProtocolConst;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;

@Slf4j
@RequiredArgsConstructor
public class VmsResDownloadForm implements VmsResponse {

    private final TbVmsCtlrDto vmsObj;
    private final VmsFramePacket resFramePacket;
    private boolean success;
    private eVmsErrorCode error;

    @Override
    public boolean process() {
        /**
         * ACK/NAK 확인
         */
        byte[] body = this.resFramePacket.getBody();
        log.info("VmsResDownloadForm.process: VMS {}, body length: {}.", this.vmsObj.getVmsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 1) {
            log.error("VmsResDownloadForm.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.success = byteBuffer.get() == VmsProtocolConst.VMS_ACK;
        if (!this.success) {
            this.error = eVmsErrorCode.ERROR_UNKNOWN;
            if (body.length > 1) {
                byte errorCode = byteBuffer.get();
                this.error = eVmsErrorCode.getValue(errorCode & 0xFF);
                if (this.error == null) {
                    log.error("VmsResDownloadForm.process: VMS {}, Unknown error code: {}.", this.vmsObj.getVmsCtlrNmbr(), String.format("%02X", errorCode & 0xFF));
                    this.error = eVmsErrorCode.ERROR_UNKNOWN;
                }
            }
        }
        else {
            this.error = eVmsErrorCode.ERROR_NONE;
        }
        log.info("{}", toString());

        if (this.error == eVmsErrorCode.ERROR_NONE) {
            if (this.vmsObj.getDownloadData().isDefault()) {
                this.vmsObj.downloadFile();
            }
            else {
                this.vmsObj.downloadAutoFixForm();
            }
        }
        return true;
    }

    public String toString() {
        StringBuilder data = new StringBuilder();
        data.append(String.format("RESPONSE-%s. VMS %d", eVmsOpCode.OP_VMS_DOWNLOAD_FORM, this.vmsObj.getVmsCtlrNmbr()));
        data.append(System.getProperty("line.separator"));
        data.append(String.format("Download Form: %s, NAK: %s", this.success, this.error));
        return data.toString();
    }

}
