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

import com.its.app.AppUtils;
import com.its.app.utils.SysUtils;
import com.its.vms.dto.TbVmsCtlrDto;
import com.its.vms.entity.VmsDsplDnldResult;
import com.its.vms.process.DbmsData;
import com.its.vms.process.DbmsDataProcess;
import com.its.vms.process.DbmsDataType;
import com.its.vms.xnettcp.vms.process.response.VmsResponse;
import com.its.vms.xnettcp.vms.protocol.VmsFramePacket;
import com.its.vms.xnettcp.vms.protocol.VmsProtocolConst;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;

@Slf4j
@RequiredArgsConstructor
public class VmsResBlank 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("VmsResBlank.process: VMS {}, body length: {}.", this.vmsObj.getVmsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 1) {
            log.error("VmsResBlank.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("VmsResBlank.process: VMS {}, Unknown error code: {}.", this.vmsObj.getVmsCtlrNmbr(), String.format("%02X", errorCode & 0xFF));
                    this.error = eVmsErrorCode.ERROR_UNKNOWN;
                }
            }
        }
        else {
            this.error = eVmsErrorCode.ERROR_NONE;
        }

        /**
         * 표출정보 제어기 다운로드 결과를 데이터베이스에 저장한다.
         */
        String dnldYn = (this.error == eVmsErrorCode.ERROR_NONE) ? "Y" : "N";
        int formCnt = this.vmsObj.getFormManager().count();
        VmsDsplDnldResult dnldResult = new VmsDsplDnldResult(this.vmsObj.getVmsCtlrNmbr(), SysUtils.getSysTime(), formCnt, dnldYn);
        DbmsDataProcess dbmsDataProcess = (DbmsDataProcess) AppUtils.getBean(DbmsDataProcess.class);
        dbmsDataProcess.add(new DbmsData(DbmsDataType.DBMS_DATA_VMS_FORM_DOWNLOAD_RESULT, false, dnldResult));

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

        return true;
    }

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

}
