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 javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
//@Component
public class AlgorithmResponseConsumerManager {

    private RedisQueueConsumerAsync<AnalyseResult> consumer;

    @Resource
    private RedisService redisService;

    @Resource
    private IAnalyseResponseService analysisService;

    @PostConstruct
    public void initConsumer() {
        consumer = new RedisQueueConsumerAsync<AnalyseResult>(
                redisService.redisTemplate,
                AnalyseConstants.ALGORITHM_RESPONSE_QUEUE,
                AnalyseResult.class,
                1000,
                500,
                response -> {
                    try {
                        log.info("AlgorithmResponseConsumerManager queueSize: {}, response: {}", getQueueSize(), response);
                        analysisService.handleAlgorithmResult(response);
                    } catch (IOException e) {
                        log.info(Color.RED + "AlgorithmResponseConsumerManager error queueSize: {}, request: {}" + Color.END, getQueueSize(), response);
                    }
                }
        );

        consumer.start();
    }

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

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

