package eu.dnetlib.data.mdstore.manager.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import eu.dnetlib.dhp.schema.mdstore.MDStoreVersion;
import eu.dnetlib.dhp.schema.mdstore.MDStoreWithInfo;
import eu.dnetlib.data.mdstore.manager.exceptions.MDStoreManagerException;
import eu.dnetlib.data.mdstore.manager.utils.ControllerUtils;
import eu.dnetlib.data.mdstore.manager.utils.DatabaseUtils;

@Controller
public class MDInspectorController {

	@Autowired
	private DatabaseUtils databaseUtils;

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

	@Value("${dhp.mdstore-manager.inspector.records.max}")
	private Long MAX_MD_RECORDS;

	@RequestMapping("/mdrecords/{id}/{limit}")
	public String mdstoreInspector(final ModelMap map, @PathVariable final String id, @PathVariable final long limit) throws MDStoreManagerException {

		final MDStoreWithInfo md;
		final MDStoreVersion ver;

		if (isMdstoreId(id)) {
			log.debug("MDSTORE: " + id);
			md = databaseUtils.findMdStore(id);
			ver = databaseUtils.findVersion(md.getCurrentVersion());
		} else {
			log.debug("VERSION: " + id);
			ver = databaseUtils.findVersion(id);
			md = databaseUtils.findMdStore(ver.getMdstore());
		}

		map.addAttribute("mdId", md.getId());
		map.addAttribute("versionId", ver.getId());

		map.addAttribute("dsId", md.getDatasourceId());
		map.addAttribute("dsName", md.getDatasourceName());
		map.addAttribute("apiId", md.getApiId());

		map.addAttribute("format", md.getFormat());
		map.addAttribute("layout", md.getLayout());
		map.addAttribute("interpretation", md.getInterpretation());

		map.addAttribute("path", ver.getHdfsPath());
		map.addAttribute("lastUpdate", ver.getLastUpdate());
		map.addAttribute("size", ver.getSize());

		map.addAttribute("limit", Math.min(limit, MAX_MD_RECORDS));

		if (md.getCurrentVersion().equals(ver.getId())) {
			map.addAttribute("status", "current");
		} else if (ver.isWriting()) {
			map.addAttribute("status", "writing");
		} else {
			map.addAttribute("status", "expired");
		}

		return "inspector";
	}

	@ExceptionHandler(Exception.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public ModelAndView handleException(final Exception e) {
		return ControllerUtils.errorPage("Metadata Inspector - ERROR", e);
	}

	private boolean isMdstoreId(final String id) {
		return id.length() < 40;
	}
}
