package com.its.vms.domain.task;

import com.its.vms.domain.NET;
import com.its.vms.dto.TbVmsCtlrDto;
import com.its.vms.xnettcp.vms.handler.VmsServerIdleStateHandler;
import com.its.vms.xnettcp.vms.protocol.VmsReqFramePacket;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.TimerTask;

@Slf4j
public class VmsCommandTimeoutTask extends TimerTask {

    private final TbVmsCtlrDto vmsObj;
    private final VmsReqFramePacket packet;
    private final int          retryCnt;

    public VmsCommandTimeoutTask(TbVmsCtlrDto vmsObj, VmsReqFramePacket packet, int retryCnt) {
        this.vmsObj = vmsObj;
        this.packet = packet;
        this.retryCnt = retryCnt;
    }

    public TbVmsCtlrDto getCtlr() {
        return this.vmsObj;
    }

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

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

    @Override
    public void run() {

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

        log.info("VmsConnectTimeoutTask-run: VSM {}, opCode {}, retryCnt {}.", this.vmsObj.getVmsCtlrNmbr(), this.packet.getOpCode(), this.retryCnt);

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

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

}
