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 me.prettyprint.cassandra.service.PoolExhaustedException;

import org.apache.commons.io.IOUtils;
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;

@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;
	
	@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, final OutputStream output) throws IllegalStateException, PoolExhaustedException, Exception {
		final String id = request.getPathInfo().replace("/store.do/", "");

		fileStore.read(id, output);
	}

}
