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

import java.nio.ByteBuffer;

@Slf4j
@RequiredArgsConstructor
public class VmsResUploadFormSchedule implements VmsResponse {

    private final TbVmsCtlrDto vmsObj;
    private final VmsFramePacket resFramePacket;
    private int scheduleCount;
    private String schedule;

    @Override
    public boolean process() {

        byte[] body = this.resFramePacket.getBody();
        log.info("VmsResUploadFormSchedule.process: VMS {}, body length: {}.", this.vmsObj.getVmsCtlrNmbr(), body != null ? body.length : 0);
        if (body == null || body.length < 30) {
            log.error("VmsResUploadFormSchedule.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);

        StringBuilder data = new StringBuilder();
        this.scheduleCount = body.length / 3;
        for (int ii = 0; ii < this.scheduleCount; ii++) {
            short formId = byteBuffer.getShort();
            byte dispTm = byteBuffer.get();
            data.append(System.getProperty("line.separator"));
            data.append(String.format("%2d 폼: ID %d, Display Second %d", ii + 1, formId, dispTm & 0x0FF));
        }
        this.schedule = data.toString();

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

        return true;
    }

    public String toString() {
        StringBuilder data = new StringBuilder();
        data.append(String.format("RESPONSE-%s. VMS %d", eVmsOpCode.OP_VMS_UPLOAD_FORM_SCHEDULE, this.vmsObj.getVmsCtlrNmbr()));
        data.append(System.getProperty("line.separator"));
        data.append(String.format("Schedule %d EA.", this.scheduleCount));
        data.append(this.schedule);
        return data.toString();
    }

}
