package com.yeejoin.amos.patrol.business.listener;

import com.yeejoin.amos.patrol.business.data.CheckRecordDataConsumer;
import com.yeejoin.amos.patrol.business.dto.CheckRecordDataDto;
import com.yeejoin.amos.patrol.business.event.CheckRecordInsertEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class CheckRecordInsertListener {

    private final BlockingQueue<CheckRecordDataDto> blockingQueue = new LinkedBlockingDeque<>();

    private int coreThreads = Runtime.getRuntime().availableProcessors() * 2;

    @Autowired
    private ApplicationContext applicationContext;

    @EventListener
    public void onApplicationEvent(CheckRecordInsertEvent event) {
        blockingQueue.add(event.getMessage());
    }

    @PostConstruct
    public void init() {
        Executor executor = Executors.newFixedThreadPool(coreThreads);
        CheckRecordDataConsumer consumer = new CheckRecordDataConsumer(blockingQueue, applicationContext);
        for (int i = 0; i < coreThreads; i++) {
            executor.execute(consumer);
        }
    }

}
