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

import com.its.app.utils.SysUtils;
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 VdsResParamUploading implements VdsResponse {

    private final TbVdsCtlrDto vdsObj;
    private final VdsFramePacket resFramePacket;
    private int dataId;
    private int dataSize;
    private String createTm;
    private int total;
    private int current;

    @Override
    public boolean process() {
        byte[] body = this.resFramePacket.getBody();
        log.info("VdsResParamUploading.process: VDS {}, body length: {}.", this.vdsObj.getVdsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 21) {
            log.error("VdsResParamUploading.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);
        this.dataId = (int)(byteBuffer.get() & 0xFF);
        this.dataSize = byteBuffer.getInt();
        byte[] crtTm = new byte[14];
        byteBuffer.get(crtTm);
        this.createTm = SysUtils.byteArrayToString(crtTm);
        this.total = (int)(byteBuffer.get() & 0xFF);
        this.current = (int)(byteBuffer.get() & 0xFF);
        if (this.dataSize > 0) {
            byte[] image = new byte[this.dataSize];
            byteBuffer.get(image);
        }
        else {
            this.dataSize = 0;
        }
        log.info("{}", toString());

        return true;
    }

    public String toString() {
        StringBuilder data = new StringBuilder();
        data.append(String.format("RESPONSE-%s. VDS %d", eVdsOpCode.OP_VDS_STATUS_RESET, this.vdsObj.getVdsCtlrNmbr()));
        data.append(System.getProperty("line.separator"));
        data.append(String.format("Image Id %d, Size %d, Create Time: %s, Total %d, Current %d.", this.dataId, this.dataSize, this.createTm, this.total, this.current));
        return data.toString();
    }

}
