/**
 * 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.gateway.queue.impl;

import com.crunii.micro.common.queue.ObjectEvent;
import com.crunii.micro.common.queue.impl.AbstractFastQueueHandler;
import com.crunii.micro.common.utils.StopUtil;
import com.crunii.micro.domain.entitysql.main.TCallLogS;
import com.crunii.micro.ds.uid.worker.UidGenerator;
import com.crunii.micro.platform.service.CallLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * @author 田平 create 2019年5月15日下午4:44:39
 */
@Slf4j
@Component
public class CallLogFastQueueHandler extends AbstractFastQueueHandler<TCallLogS> {

	@Value("${spring.application.name}")
	private String appName;

	@Autowired
	private CallLogService callLogService;

	private ExecutorService executor = new ThreadPoolExecutor(4, 8, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(512),
			new RejectedExecutionHandler() {
				@Override
				public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
					if (!executor.isShutdown()) {
						try {
							executor.getQueue().put(r);
						} catch (InterruptedException e) {
							log.warn("executor Interrupted", e);
						}
					}
				}
			});

	@PreDestroy
	public void destroy() {
		log.info("CallLogFastQueueHandler stop executor!");
		StopUtil.stopES(executor);
	}

	@Override
	public void handler(ObjectEvent<TCallLogS> event, long sequence, boolean endOfBatch) {
		TCallLogS callLog = event.getVal();
		if (callLog == null) {
			log.info("callLog is null");
			return;
		}
		sendAsync(callLog);
		//释放资源,必须释放否则可能引起内存溢出
		event.clear();
	}

	private void sendAsync(TCallLogS callLog) {
		executor.execute(() -> createCallLogDirect(callLog));
	}

	public void createCallLogDirect(TCallLogS callLog) {
		try {
			callLogService.createTCallLog(callLog);
		} catch (Exception e) {
			log.error("Direct insert database error!{}", callLog, e);
		}
	}

}
