/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.platform.log.impl;

import com.crunii.micro.common.queue.FastQueue;
import com.crunii.micro.common.queue.impl.FastQueueImpl;
import com.crunii.micro.domain.entitysql.main.TSqlLogS;
import com.crunii.micro.platform.log.SqlLogHandler;
import com.lmax.disruptor.dsl.ProducerType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 田平 create 2019年5月15日下午4:58:21
 */
@Component
@Slf4j
public class SqlLogHandlerImpl implements SqlLogHandler, ApplicationListener<ApplicationStartedEvent> {

	@Autowired
	private SqlLogFastQueueHandler sqlLogFastQueueHandler;

	private FastQueue<TSqlLogS> fastQueue;

	private volatile boolean started;

	private List<TSqlLogS> initSqlLogs = Collections.synchronizedList(new ArrayList<>());

	@Override
	public void onApplicationEvent(ApplicationStartedEvent event) {
		started = true;
		log.info("execute send initSqlLogs size:{} to fastQueue!", initSqlLogs.size());
		initSqlLogs.forEach(this::doSqlLog);
		initSqlLogs.clear();
	}

	@Override
	public void doSqlLog(TSqlLogS sqlLog) {
		//项目启动完成前可能会执行一些sql，这个时候负载均衡的相关bean没有加载好，无法执行
		//等springboot加载完成后再执行
		if (started) {
			fastQueue.add(sqlLog);
		} else {
			initSqlLogs.add(sqlLog);
		}
	}

	@PostConstruct
	public void init() {
		fastQueue = new FastQueueImpl<>(1024 * 64, ProducerType.MULTI, sqlLogFastQueueHandler);
		fastQueue.init();
	}

	@PreDestroy
	public void destroy() {
		if (fastQueue != null) {
			fastQueue.destroy();
		}
	}
}
