package com.its.dsrc.xnettcp.dsrc.task;

import com.its.app.AppUtils;
import com.its.dsrc.dao.mapper.RseCtlrMapper;
import com.its.dsrc.entity.TbRseCtlr;
import com.its.dsrc.entity.TbRseCtrlHs;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.TimerTask;

@Slf4j
public class DsrcAsn1TimeoutTask extends TimerTask {

    private final TbRseCtlr obj;
    private final Long      packetNmbr;

    public DsrcAsn1TimeoutTask(TbRseCtlr obj, Long packetNmbr) {
        this.obj = obj;
        this.packetNmbr = packetNmbr;
    }

    @Override
    public void run() {

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

        //log.info("DsrcAsn1TimeoutTask-run: packetNmbr: {}, obj: {}", this.packetNmbr, this.obj.toString());
        log.info("DsrcAsn1TimeoutTask-run: packetNmbr: {}, obj: {}", this.packetNmbr, this.obj.getID());
        this.obj.removeRegisteredCommands(this.packetNmbr, false);
        TbRseCtrlHs command = this.obj.getUserCommands(this.packetNmbr);
        if (command != null) {
            this.obj.removeUserCommands(this.packetNmbr);
            // TODO: 제어명령 성공 전송(실패)
            command.setRspsType("5");  // 명령 실패(타임아웃)로 설정
            RseCtlrMapper mapper = (RseCtlrMapper) AppUtils.getBean(RseCtlrMapper.class);
            mapper.updateRseCtrlHs(command);
        }

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