package com.inspect.analysis.service.impl;

import com.inspect.analysis.constant.AnalyseConstants;
import com.inspect.analysis.domain.AnalyseResult;
import com.inspect.analysis.service.IAnalyseResponseService;
import com.inspect.base.core.constant.Color;
import com.inspect.base.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Component
public class AlgorithmResponseRetryableConsumerManager {

    private RedisQueueRetryableConsumerAsync<AnalyseResult> consumer;
    @Resource
    private RedisService redisService;

    @Resource
    private IAnalyseResponseService analysisService;

    private final ExecutorService executor = Executors.newFixedThreadPool(10);

    @PostConstruct
    public void initConsumer() {
        consumer = new RedisQueueRetryableConsumerAsync<AnalyseResult>(
                redisService.redisTemplate,
                AnalyseConstants.ALGORITHM_RESPONSE_QUEUE,
                AnalyseResult.class,
                1.0,
                500,
                response -> executor.submit(() -> {
                    try {
                        log.info("ALGORITHM_RESPONSE_RETRYABLE_CONSUME_MANAGE queueSize: {}, reqeustId: {}, patrolId: {}",
                                getQueueSize(),
                                response.getRequestId(),
                                response.getTaskPatrolId());
                        long start = System.currentTimeMillis();
                        analysisService.handleAlgorithmResult(response);
                        log.info("ALGORITHM_RESPONSE_RETRYABLE_CONSUME_MANAGE COST: {}, reqeustId: {}, patrolId: {}",
                                System.currentTimeMillis() - start,
                                response.getRequestId(),
                                response.getTaskPatrolId());
                    } catch (IOException e) {
                        log.info(Color.RED + "ALGORITHM_RESPONSE_RETRYABLE_CONSUME_MANAGE error queueSize: {}, request: {}, Msg: {}" + Color.END,
                                getQueueSize(),
                                response,
                                e.getMessage());
                    }
                })
        );

        consumer.start();
    }

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

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

