package eu.dnetlib.functionality.modular.ui;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.ui.ModelMap;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import eu.dnetlib.miscutils.datetime.DateUtils;
import eu.dnetlib.miscutils.datetime.HumanTime;

public class InfoController extends ModuleEntryPoint implements ResourceLoaderAware {

	private String hostname;
	private String port;
	private String context;

	private ResourceLoader resourceLoader;

	private static final Log log = LogFactory.getLog(InfoController.class);

	@Override
	protected void initialize(final ModelMap map, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		final RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();

		final Map<String, Map<String, String>> info = Maps.newLinkedHashMap();
		info.put("General", getGeneralInfo(mxbean));
		info.put("JVM", getJvmInfo(mxbean));
		info.put("Libraries and arguments", getLibInfo(mxbean));
		info.put("System properties", getSysInfo(mxbean));

		map.addAttribute("info", info);
		map.addAttribute("modules", getModules());

	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> getModules() throws IOException {
		final Map<String, Map<String, Map<String, Object>>> modules = Maps.newLinkedHashMap();

		final MavenXpp3Reader reader = new MavenXpp3Reader();
		for (Resource res : ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath*:/META-INF/**/pom.xml")) {
			try {
				final Model model = reader.read(res.getInputStream());

				final String name = model.getArtifactId();

				String groupId = model.getGroupId();
				for (Parent parent = model.getParent(); groupId == null && model.getParent() != null; parent = model.getParent()) {
					groupId = parent.getGroupId();
				}

				String version = model.getVersion();
				for (Parent parent = model.getParent(); version == null && model.getParent() != null; parent = model.getParent()) {
					version = parent.getVersion();
				}

				if (!modules.containsKey(groupId)) {
					modules.put(groupId, new HashMap<String, Map<String, Object>>());
				}
				if (!modules.get(groupId).containsKey(name)) {
					final Map<String, Object> map = Maps.newHashMap();
					map.put("group", groupId);
					map.put("name", name);
					map.put("files", new ArrayList<String>());
					map.put("versions", new ArrayList<String>());
					modules.get(groupId).put(name, map);
				} else {
					// Artifact already found
					modules.get(groupId).get(name).put("warning", "1");
				}
				((List<String>) modules.get(groupId).get(name).get("versions")).add(version);
				((List<String>) modules.get(groupId).get(name).get("files")).add(res.getURI().toString());
			} catch (Exception e) {
				log.error("Error evaluating pom: " + res.getURI());
				log.debug("-- ERROR --", e);
			}
		}

		final List<Map<String, Object>> list = Lists.newArrayList();
		for (Entry<String, Map<String, Map<String, Object>>> e : modules.entrySet()) {
			for (Entry<String, Map<String, Object>> e1 : e.getValue().entrySet()) {
				list.add(e1.getValue());
			}
		}

		Collections.sort(list, new Comparator<Map<String, Object>>() {

			@Override
			public int compare(final Map<String, Object> o1, final Map<String, Object> o2) {
				if (o1.get("group").equals(o2.get("group"))) {
					return o1.get("name").toString().compareTo(o2.get("name").toString());
				} else {
					return o1.get("group").toString().compareTo(o2.get("group").toString());
				}
			}
		});

		return list;
	}

	private Map<String, String> getSysInfo(final RuntimeMXBean mxbean) {
		return mxbean.getSystemProperties();
	}

	private Map<String, String> getGeneralInfo(final RuntimeMXBean mxbean) {
		final Map<String, String> genInfo = Maps.newLinkedHashMap();
		genInfo.put("Hostname", hostname);
		genInfo.put("Port", port);
		genInfo.put("Context", context);
		genInfo.put("Uptime", HumanTime.exactly(mxbean.getUptime()));
		genInfo.put("Start Time", DateUtils.calculate_ISO8601(mxbean.getStartTime()));
		return genInfo;
	}

	private Map<String, String> getJvmInfo(final RuntimeMXBean mxbean) {
		final Map<String, String> jvmInfo = Maps.newLinkedHashMap();
		jvmInfo.put("JVM Name", mxbean.getVmName());
		jvmInfo.put("JVM Vendor", mxbean.getVmVendor());
		jvmInfo.put("JVM Version", mxbean.getVmVersion());
		jvmInfo.put("JVM Spec Name", mxbean.getSpecName());
		jvmInfo.put("JVM Spec Vendor", mxbean.getSpecVendor());
		jvmInfo.put("JVM Spec Version", mxbean.getSpecVersion());
		jvmInfo.put("Running JVM Name", mxbean.getName());
		jvmInfo.put("Management Spec Version", mxbean.getManagementSpecVersion());
		return jvmInfo;
	}

	private Map<String, String> getLibInfo(final RuntimeMXBean mxbean) {
		final Map<String, String> libInfo = Maps.newLinkedHashMap();
		libInfo.put("Classpath", mxbean.getClassPath().replaceAll(":", " : "));
		libInfo.put("Boot ClassPath", mxbean.getBootClassPath().replaceAll(":", " : "));
		libInfo.put("Input arguments", mxbean.getInputArguments().toString());
		libInfo.put("Library Path", mxbean.getLibraryPath().replaceAll(":", " : "));
		return libInfo;
	}

	public String getHostname() {
		return hostname;
	}

	@Required
	public void setHostname(final String hostname) {
		this.hostname = hostname;
	}

	public String getPort() {
		return port;
	}

	@Required
	public void setPort(final String port) {
		this.port = port;
	}

	public String getContext() {
		return context;
	}

	@Required
	public void setContext(final String context) {
		this.context = context;
	}

	@Override
	public void setResourceLoader(final ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}
}
