package com.inspect.analysis.service.impl;

import com.inspect.analysis.constant.AnalyseConstants;
import com.inspect.base.core.constant.Color;
import com.inspect.base.redis.service.RedisService;
import com.inspect.partrolresult.domain.AnalyseRequest;
import com.inspect.partrolresult.service.IAnalyseRequestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.annotation.PreDestroy;

//@Component
public class AlgorithmRequestConsumerManager {
    private static final Logger log = LoggerFactory.getLogger(AlgorithmRequestConsumerManager.class);

    private RedisQueueConsumerAsync<AnalyseRequest> consumer;

    @Resource
    private RedisService redisService;

    @Resource
    private IAnalyseRequestService analyseRequestService;

    @PostConstruct
    public void initConsumer() {
        consumer = new RedisQueueConsumerAsync<AnalyseRequest>(
                redisService.redisTemplate,
                AnalyseConstants.ALGORITHM_REQUEST_QUEUE,
                AnalyseRequest.class,
                1000,
                500,
                request -> {
                    try {
                        log.info("AlgorithmRequestConsumerManager queueSize: {}, request: {}", getQueueSize(), request);
                        analyseRequestService.sendRequest(request, request.getTypeList(), request.isFilter());
                    } catch (Exception e) {
                        log.info(Color.RED + "AlgorithmRequestConsumerManager error queueSize: {}, request: {}" + Color.END, getQueueSize(), request);
                    }
                }
        );

        consumer.start(); // 应用启动时即开始消费
    }

    @PreDestroy
    public void stopConsumer() {
        if (consumer != null) {
            consumer.stop();
        }
    }

    public long getQueueSize() {
        return redisService.redisTemplate.opsForList().size(AnalyseConstants.ALGORITHM_REQUEST_QUEUE);
    }
}

