package com.tsi.comm.server.kafka;

import com.tsi.app.common.app.AppUtils;
import com.tsi.app.common.utils.TimeUtils;
import com.tsi.comm.server.mybatis.vo.AbstractDbmsVo;
import com.tsi.comm.server.mybatis.vo.KafkaTransVo;
import com.tsi.comm.server.process.dbms.TsiCvimDbmsProcess;
import com.tsi.comm.server.repository.TsiTpmsManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.listener.MessageListener;
import org.springframework.kafka.support.Acknowledgment;

import java.util.concurrent.TimeUnit;

@Slf4j
public class TsiKafkaConsumerWorker implements MessageListener<String, Long> {

    private TsiCvimDbmsProcess tsiCvimDbmsService;

    public TsiKafkaConsumerWorker() {
        this.tsiCvimDbmsService = (TsiCvimDbmsProcess) AppUtils.getBean(TsiCvimDbmsProcess.class);
    }

    @Override
    public void onMessage(ConsumerRecord<String, Long> record) {
        Long sendNanoTime = record.value();
        Long recvNanoTime = System.nanoTime();

        KafkaTransVo stat = new KafkaTransVo(AbstractDbmsVo.DBMS_KAFKA_TRANS_HS);
        stat.setHostName(TsiTpmsManager.getInstance().getKafkaTransVo().getHostName());
        stat.setStatus(1);
        if (TsiTpmsManager.getInstance().getKafkaTransVo().getSendNanoTime() == sendNanoTime) {
            stat.setSendTm(TsiTpmsManager.getInstance().getKafkaTransVo().getSendTm());
            stat.setRecvTm(TimeUnit.MICROSECONDS.convert(Math.abs(recvNanoTime - sendNanoTime), TimeUnit.NANOSECONDS));
        }
        else {
            stat.setRecvTm(TimeUnit.MICROSECONDS.convert(Math.abs(recvNanoTime - sendNanoTime), TimeUnit.NANOSECONDS));
            stat.setSendTm(stat.getRecvTm());
            log.info("recv ping success, sendNanoTime miss match: {}, {}", sendNanoTime, TimeUtils.elapsedTimeStr(recvNanoTime - sendNanoTime));
        }
        tsiCvimDbmsService.add(stat, (int)Thread.currentThread().getId());
        log.info("recv ping success: {}, {}", sendNanoTime, TimeUtils.elapsedTimeStr(recvNanoTime - sendNanoTime));
    }

    @Override
    public void onMessage(ConsumerRecord<String, Long> record, Acknowledgment acknowledgment) {
        try {
            Long sendNanoTime = record.value();
            Long recvNanoTime = System.nanoTime();
            log.info("recv ping success, ack: {}, {}", sendNanoTime, TimeUtils.elapsedTimeStr(recvNanoTime - sendNanoTime));
            //acknowledgment.acknowledge();
        } catch (Exception e) {
            log.error("onMessage：" + e.getMessage());
        }
    }

}
