package com.eactive.eai.common.logger.async;

import java.util.ArrayList;
import java.util.List;

import com.eactive.eai.common.logger.EAILogException;
import com.eactive.eai.common.logger.EAILogSender;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.lmax.disruptor.EventHandler;

public class CustomEventHandler implements EventHandler<LoggingEvent> {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	String name;
	int sleepMs;
	private int batchSize = 1;
	
	private int count = 0;
    private final List<LoggingEvent> eventList = new ArrayList<>();
    
	public CustomEventHandler() {
	}

	public CustomEventHandler(String name, int sleepMs, int batchSize) {
		this.name = name;
		this.sleepMs = sleepMs;
		this.batchSize = batchSize;
	}

	@Override
	public void onEvent(LoggingEvent event, long sequence, boolean endOfBatch) throws Exception {
		if(sleepMs > 0) Thread.sleep(sleepMs);
		if(batchSize > 1) {
			eventList.add(event);
	        if (++count >= batchSize) {
	            processBatch();
	            eventList.clear();
	            count = 0;
	        }
		}
		else {
			EAIMessage message = event.getMessage();
			if(logger.isInfo()) {
				logger.info(String.format("CustomWorkHandler: %s LoggingEvent: %s %s\n"
						,name, message.getSvcOgNo() ,message.getLogPssSno())
						);
			}
			EAILogSender.logDirect(event.getMessage(), event.getProperty());
			if(event != null) {
				event.clear();
				event = null;
			}
		}        
	}

	private void processBatch() throws EAILogException {
		for(LoggingEvent event:eventList) {			
			EAILogSender.logDirect(event.getMessage(), event.getProperty());	
		}
	}
}
