package com.tuoheng.common.config.kafka;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.KafkaException;
import org.springframework.kafka.core.KafkaProducerException;
import org.springframework.kafka.core.KafkaSendCallback;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;

@Component
@ConditionalOnProperty(name = KafkaPropeties.SPRING_KAFKA_ENABLE, havingValue = KafkaPropeties.TRUE)
public class KafkaService {
    private static final Logger LOGGER = LoggerFactory.getLogger(KafkaService.class);

    // 同步发送消息超时时间<s>
    private static final int TIMEOUT = 20;

    @Autowired
    @Qualifier("kafkaTemplate")
    private KafkaTemplate<String, String> template;

    /**
     * 异步发送
     * @param record 消息生产者
     */
    public void sendAsynchronous(ProducerRecord<String, String> record,
        Consumer<SendResult<String, String>> succussEvent,
        Consumer<KafkaProducerException> failEvent){
        ListenableFuture<SendResult<String, String>> future = template.send(record);
        future.addCallback(new KafkaSendCallback<String, String>() {
            @Override
            public void onSuccess(SendResult<String, String> result) {
                Optional.ofNullable(succussEvent).ifPresent((succussEvent)->{succussEvent.accept(result);});
            }
            @Override
            public void onFailure(KafkaProducerException ex) {
                Optional.ofNullable(failEvent).ifPresent((failEvent)->{failEvent.accept(ex);});
                LOGGER.error("消息异步发送异常", ex);
                throw new KafkaException("消息异步发送异常");
            }
        });
    }

    /**
     * 异步发送
     * @param record 消息生产者
     */
    public void sendAsynchronous(ProducerRecord<String, String> record){
        template.send(record);
    }

    /**
     * 同步发送
     * @param record 消息生产者
     */
    public void sendSync(ProducerRecord<String, String> record) {
        try {
            template.send(record).get(TIMEOUT, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            LOGGER.error("消息同步发送异常", e);
            throw new KafkaException("消息发送异常，请重试");
        } catch (TimeoutException | InterruptedException e) {
            LOGGER.error("消息同步发送超时", e);
            throw new KafkaException("消息发送超时，请重试");
        }
    }

    /**
     * 同步发送
     * @param topic topic
     * @param message 消息
     */
    public void sendSync(String topic, String message) {
        try {
            template.send(topic, message).get(TIMEOUT, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            LOGGER.error("消息同步发送异常", e);
            throw new KafkaException("消息发送异常，请重试");
        } catch (TimeoutException | InterruptedException e) {
            LOGGER.error("消息同步发送超时", e);
            throw new KafkaException("消息发送超时，请重试");
        }
    }

    /**
     * 同步发送
     * @param topic topic
     * @param message 消息
     */
    public void sendSync(String topic, String key, String message) {
        try {
            template.send(topic, key, message).get(TIMEOUT, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            LOGGER.error("消息同步发送异常", e);
            throw new KafkaException("消息发送异常，请重试");
        } catch (TimeoutException | InterruptedException e) {
            LOGGER.error("消息同步发送超时", e);
            throw new KafkaException("消息发送超时，请重试");
        }
    }
}
