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

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ElinkConfig;

public class LoggingPoolObjectFactory extends BasePooledObjectFactory<LoggingPoolObject> {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private static int i = 0;
	public LoggingPoolObjectFactory() {
		// empty
	}

	@Override
	public LoggingPoolObject create() throws Exception {
		int queueSize = ElinkConfig.getAsyncQueueSize();
		int workers = ElinkConfig.getAsyncWorkers();
		String waitStrategy = ElinkConfig.getWaitStrategy();
		return new LoggingPoolObject(i++, queueSize, workers, waitStrategy);
	}

	@Override
	public PooledObject<LoggingPoolObject> wrap(LoggingPoolObject object) {
		return new DefaultPooledObject<>(object);
	}
	
	@Override
    public void passivateObject(PooledObject<LoggingPoolObject> pooledObject) {
		// empty
    }
	@Override
    public void destroyObject(PooledObject<LoggingPoolObject> pooledObject) {
		LoggingPoolObject loggingPoolObject = pooledObject.getObject();
		if(logger.isWarn()) {
			logger.warn("destroyObject - {}", loggingPoolObject.toString());
		}
		loggingPoolObject.shutdown();
    }
}