package eu.dnetlib.vocabularies.publisher.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import eu.dnetlib.vocabularies.publisher.VocabularyNotFoundException;
import eu.dnetlib.vocabularies.publisher.VocabularyRetriever;
import eu.dnetlib.vocabularies.publisher.model.Vocabulary;

@Controller
public class VocabularyPublisherController {

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

	@Resource
	private VocabularyRetriever vocabularyRetriever;
	@Value("${vocabulary.publisher.title}")
	private String title;
	@Value("${vocabulary.publisher.baseURL}")
	private String baseURL;
	@Value("${container.context}")
	private String context;

	@RequestMapping(value = "/vocabularies", method = RequestMethod.GET, produces = { "application/json" })
	public @ResponseBody
	List<Vocabulary> listVocabularies() {
		log.debug("listVocabularies()");
		return vocabularyRetriever.listVocabularies();
	}

	@RequestMapping(value = "/vocabularies/{code}", method = RequestMethod.GET, produces = { "application/json" })
	public @ResponseBody
	Vocabulary getVocabulary(@PathVariable("code") final String code) throws VocabularyNotFoundException {
		log.debug("getVocabulary with code = " + code);
		return this.vocabularyRetriever.getVocabularyByCode(code);
	}

	// View-based methods for html responses
	@RequestMapping(value = "/vocabularies", method = RequestMethod.GET, produces = { "text/html" })
	public void listVocabularies(final ModelMap map) {
		map.addAttribute("vocabularies", listVocabularies());
		map.addAttribute("title", title);
		map.addAttribute("baseURL", baseURL);
		map.addAttribute("context", context);
	}

	@RequestMapping(value = "/vocabularies/{code}", method = RequestMethod.GET, produces = { "text/html" })
	public String getVocabulary(@PathVariable("code") final String code, final ModelMap map) throws VocabularyNotFoundException {
		map.addAttribute("vocabulary", getVocabulary(code));
		map.addAttribute("baseURL", baseURL);
		map.addAttribute("context", context);
		return "displayVocabulary";
	}

}
