package eu.dnetlib.r2d2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;

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

import me.prettyprint.cassandra.service.PoolExhaustedException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import eu.dnetlib.r2d2.cassandra.CassandraFileStore;
import eu.dnetlib.r2d2.neo4j.dao.ItemDao;
import eu.dnetlib.r2d2.neo4j.domain.Neo4jItem;

@Controller
public class FileController {
	private static final Log log = LogFactory.getLog(FileController.class); // NOPMD by marko on 11/24/08 5:02 PM

	@Resource
	private FileStore fileStore;

	@Resource
	private ItemDao itemDao;

	@RequestMapping(value = "/store.do/*", method = RequestMethod.POST)
	void upload(final HttpServletRequest request, final InputStream input, final Writer writer) throws IllegalStateException, PoolExhaustedException,
			Exception {
		final String id = request.getPathInfo().replace("/store.do/", "");

		fileStore.write(id, input);

		writer.write("saved " + id);
	}

	@RequestMapping(value = "/store.do/*", method = RequestMethod.GET)
	void download(final HttpServletRequest request, HttpServletResponse response, final OutputStream output) throws IllegalStateException,
			PoolExhaustedException, Exception {
		final String id = request.getPathInfo().replace("/store.do/", "");

		Neo4jItem item = itemDao.getBean(id);

		String fileName = id;
		if (item != null) {
			fileName = StringUtils.abbreviate(item.getTitle(), 26) + ".pdf";
		} else {
			if (fileName.endsWith(".pdf"))
				fileName += ".pdf";
		}

		response.setContentType("application/pdf");
		response.addHeader("content-disposition", "attachment; filename=" + fileName);

		fileStore.read(id, output);
	}

}
