package eu.dnetlib.is.resources;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import eu.dnetlib.common.controller.AbstractDnetController;
import eu.dnetlib.data.is.resource.model.SimpleResource;
import eu.dnetlib.is.errors.InformationServiceException;
import eu.dnetlib.is.util.XmlIndenter;

public class AbstractResourceController extends AbstractDnetController {

	@Autowired
	protected SimpleResourceService service;

	@GetMapping("/{typeId}")
	public List<SimpleResource> listResources(@PathVariable final String typeId) {
		return service.listResources(typeId);
	}

	@GetMapping("/{resId}/metadata")
	public SimpleResource getMetadata(@PathVariable final String resId) throws InformationServiceException {
		return service.getMetadata(resId);
	}

	@GetMapping("/{resId}/content")
	public void getContent(@PathVariable final String resId, final HttpServletResponse res) throws InformationServiceException {
		final String ctype = service.getContentType(resId);

		res.setCharacterEncoding(StandardCharsets.UTF_8.name());
		res.setContentType(ctype);

		final String content =
			ctype.equals(MediaType.APPLICATION_XML_VALUE) ? XmlIndenter.indent(service.getContent(resId)) : service.getContent(resId);

		try {
			IOUtils.write(content, res.getOutputStream(), StandardCharsets.UTF_8.name());
		} catch (final IOException e) {
			throw new InformationServiceException("Error retrieving content", e);
		}
	}

}
