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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
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.data.mdstore.manager.exceptions.MDStoreManagerException;
import eu.dnetlib.data.mdstore.manager.utils.ControllerUtils;
import eu.dnetlib.data.mdstore.manager.utils.DatabaseUtils;
import eu.dnetlib.data.mdstore.manager.utils.ZeppelinClient;
import eu.dnetlib.dhp.schema.mdstore.MDStoreWithInfo;

@Controller
public class ZeppelinController {

	@Autowired
	private ZeppelinClient zeppelinClient;

	@Autowired
	private DatabaseUtils databaseUtils;

	@RequestMapping("/zeppelin/{mdId}/{note}")
	public String goToZeppelin(@PathVariable final String mdId, final @PathVariable String note) throws MDStoreManagerException {
		final MDStoreWithInfo mdstore = databaseUtils.findMdStore(mdId);
		final String currentVersion = mdstore.getCurrentVersion();
		final String path = databaseUtils.findVersion(currentVersion).getHdfsPath() + "/store";
		return "redirect:" + zeppelinClient.zeppelinNote(note, mdstore, path);
	}

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

}
