package com.atlassian.stash.internal.event;

import com.atlassian.event.config.EventThreadPoolConfiguration;
import com.atlassian.bitbucket.util.PropertiesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Implementation of {@link EventThreadPoolConfiguration} that configures the event dispatcher thread pool based on
 * properties in {@code bitbucket.properties}. Simple expressions are supported for these parameters, allowing for
 * configuration relative to the number of available CPUs.
 * 
 * @since 1.3
 */
@Component("eventThreadPoolConfiguration")
public class DefaultEventThreadPoolConfiguration implements EventThreadPoolConfiguration {

    private final int corePoolSize;
    private final int maxPoolSize;
    private final long keepAliveTime;

    @Autowired
    public DefaultEventThreadPoolConfiguration(
            @Value("${event.dispatcher.core.threads}") String coreThreads,
            @Value("${event.dispatcher.keepAlive}") String keepAlive,
            @Value("${event.dispatcher.max.threads}") String maxThreads) {

        corePoolSize = PropertiesUtils.parseExpression(coreThreads, 4);
        keepAliveTime = PropertiesUtils.parseExpression(keepAlive, 60);
        maxPoolSize = PropertiesUtils.parseExpression(maxThreads, Runtime.getRuntime().availableProcessors());
    }
    
    @Override
    public int getCorePoolSize() {
        return corePoolSize;
    }

    @Override
    public int getMaximumPoolSize() {
        return maxPoolSize;
    }

    @Override
    public long getKeepAliveTime() {
        return keepAliveTime;
    }

    @Override
    public TimeUnit getTimeUnit() {
        return TimeUnit.SECONDS;
    }
}
