package com.its.vds.domain.task;

import com.its.vds.domain.NET;
import com.its.vds.dto.TbVdsCtlrDto;
import com.its.vds.xnettcp.vds.handler.VdsServerIdleStateHandler;
import com.its.vds.xnettcp.vds.protocol.VdsReqFramePacket;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.TimerTask;

@Slf4j
public class VdsCommandTimeoutTask extends TimerTask {

    private final TbVdsCtlrDto      vdsObj;
    private final VdsReqFramePacket packet;
    private final int               retryCnt;

    public VdsCommandTimeoutTask(TbVdsCtlrDto vdsObj, VdsReqFramePacket packet, int retryCnt) {
        this.vdsObj = vdsObj;
        this.packet = packet;
        this.retryCnt = retryCnt;
    }

    public TbVdsCtlrDto getCtlr() {
        return this.vdsObj;
    }

    public VdsReqFramePacket getPacket() {
        return this.packet;
    }

    public short getPacketNmbr() {
        return this.packet.getPacketNmbr();
    }

    @Override
    public void run() {

        MDC.put("id", this.vdsObj.getLogKey());

        log.info("VdsCommandTimeoutTask-run: VDS {}, opCode {}, retryCnt {}.", this.vdsObj.getVdsCtlrNmbr(), this.packet.getOpCode(), this.retryCnt);

        if (this.vdsObj.getNetState() > NET.CLOSED) {
            if (this.retryCnt >= 3) {
                log.error("VdsCommandTimeoutTask-run: VDS {}, opCode {}, retryCnt {}, Command Retry Time out, will be closed.", this.vdsObj.getVdsCtlrNmbr(), this.packet.getOpCode(), this.retryCnt);
                VdsServerIdleStateHandler.disconnectChannel(this.vdsObj, this.vdsObj.getChannel());
            }
            else {
                this.vdsObj.sendData(this.packet, this.retryCnt+1);
            }
        }
        else {
            log.info("VdsCommandTimeoutTask-run: VDS {}, opCode {}, Network Already Closed.", this.vdsObj.getVdsCtlrNmbr(), this.packet.getOpCode());
        }

        MDC.remove(this.vdsObj.getLogKey());
        MDC.clear();
    }

}
