package eu.dnetlib.scholix.api;

import org.springdoc.core.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import eu.dnetlib.common.app.AbstractDnetApp;
import io.micrometer.core.aop.TimedAspect;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;

@SpringBootApplication
@EnableCaching
@EnableScheduling
@ComponentScan(basePackages = "eu.dnetlib")
public class MainApplication extends AbstractDnetApp {

	private final double scale = 1000000000;

	private final double[] histogramValues = new double[] {
		.005 * scale, .01 * scale, .25 * scale, .5 * scale, .75 * scale, scale, 2.5 * scale, 5.0 * scale, 7.5 * scale, 10.0 * scale
	};

	@Value("${dhp.swagger.api.host}")
	private String swaggetHost;

	@Value("${dhp.swagger.api.basePath}")
	private String swaggerPath;

	public static void main(final String[] args) {
		SpringApplication.run(MainApplication.class, args);
	}

	@Bean
	public TaggedCounter myCounter(final MeterRegistry meterRegistry) {

		return new TaggedCounter(ScholixAPIConstants.SCHOLIX_MANAGER_COUNTER_NAME, ScholixAPIConstants.SCHOLIX_MANAGER_TAG_NAME, meterRegistry);
	}

	@Bean
	public TimedAspect timedAspect(final MeterRegistry meterRegistry) {
		final MeterFilter mf = new MeterFilter() {

			@Override
			public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
				if (id.getName().startsWith(ScholixAPIConstants.SCHOLIX_COUNTER_PREFIX)) {

					return DistributionStatisticConfig.builder()
						.percentilesHistogram(false)
						.serviceLevelObjectives(histogramValues)
						.build()
						.merge(config);
				}
				return config;
			}
		};
		meterRegistry.config().meterFilter(mf);
		return new TimedAspect(meterRegistry);
	}

	@Bean
	public GroupedOpenApi publicApiV1() {
		return GroupedOpenApi.builder()
			.group(ScholixAPIConstants.API_V1_NAME)
			.pathsToMatch("/v1/**")
			.build();
	}

	@Bean
	public GroupedOpenApi publicApiV2() {
		return GroupedOpenApi.builder()
			.group(ScholixAPIConstants.API_V2_NAME)
			.pathsToMatch("/v2/**")
			.build();
	}

	@Override
	protected String swaggerTitle() {
		return "ScholeExplorer APIs";
	}

	@Override
	protected String swaggerDesc() {
		return ScholixAPIConstants.API_DESCRIPTION;
	}

}
