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

import com.eactive.eai.common.util.Logger;
import com.eactive.eai.env.ElinkConfig;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

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

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

    @Override
    public PooledObject<HttpLoggingPoolObject> wrap(HttpLoggingPoolObject object) {
        return new DefaultPooledObject<>(object);
    }

    @Override
    public void passivateObject(PooledObject<HttpLoggingPoolObject> pooledObject) {
        // empty
    }

    @Override
    public void destroyObject(PooledObject<HttpLoggingPoolObject> pooledObject) {
        HttpLoggingPoolObject loggingPoolObject = pooledObject.getObject();
        if(logger.isWarn()) {
            logger.warn("destroyObject - {}", loggingPoolObject.toString());
        }
        loggingPoolObject.shutdown();
    }
}
