package com.atlassian.bitbucket.mesh.boot;

import com.atlassian.util.profiling.ProfilerConfiguration;
import com.atlassian.util.profiling.Timers;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;

import static com.atlassian.bitbucket.mesh.rpc.ManagedConfigurationProperties.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class ProfilingApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment env = event.getEnvironment();

        ProfilerConfiguration configuration = Timers.getConfiguration();
        configuration.setEnabled(env.getProperty(PROFILING_ENABLED, Boolean.class, Boolean.FALSE));
        configuration.setMinFrameTime(env.getProperty(PROFILING_MIN_FRAME_TIME, Integer.class, 0), MILLISECONDS);
        configuration.setMinTraceTime(env.getProperty(PROFILING_MIN_TRACE_TIME, Integer.class, 0), MILLISECONDS);
        configuration.setMaxFrameNameLength(
                Math.max(150, env.getProperty(PROFILING_MAX_FRAME_NAME_LENGTH, Integer.class, 300)));
    }
}
