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

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

    private final TbVmsCtlrDto vmsObj;
    private final VmsFramePacket 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("VmsResStopImage.process: VMS {}, body length: {}.", this.vmsObj.getVmsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 21) {
            log.error("VmsResStopImage.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.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. VMS %d", eVmsOpCode.OP_VMS_STOP_IMAGE_REQ, this.vmsObj.getVmsCtlrNmbr()));
        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();
    }

}
