package eu.dnetlib.common.app;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

import javax.annotation.PostConstruct;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import io.micrometer.core.instrument.ImmutableTag;
import io.micrometer.core.instrument.Metrics;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

public abstract class AbstractDnetApp {

	@Value("${maven.pom.path}")
	private ClassPathResource pom;

	private static final Logger log = LoggerFactory.getLogger(AbstractDnetApp.class);

	@PostConstruct
	public void init() {
		final MavenXpp3Reader reader = new MavenXpp3Reader();
		try {
			final Model model = reader.read(new InputStreamReader(pom.getInputStream()));

			log.info(String.format("registering metric for %s", model.getArtifactId()));

			final ImmutableTag tag1 = new ImmutableTag("component", model.getGroupId() + ":" + model.getArtifactId());
			final ImmutableTag tag2 = new ImmutableTag("version", model.getVersion());
			final ImmutableTag tag3 = new ImmutableTag("scmtag", model.getScm().getTag());

			Metrics.gauge("micrometer_info", Arrays.asList(tag1, tag2, tag3), 1);
		} catch (IOException | XmlPullParserException e) {
			log.error("Error registering metric", e);
		}
	}

	@Bean
	public Docket newSwaggerDocket() {
		log.info("Initializing SWAGGER...");

		final Docket docket = new Docket(DocumentationType.SWAGGER_2);

		configSwagger(docket);

		return docket;
	}

	protected abstract void configSwagger(final Docket docket);

}
