package dynamo.services;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import dynamo.backlog.BackLogProcessor;
import dynamo.backlog.tasks.files.DeleteFileTask;
import dynamo.core.manager.DAOManager;
import dynamo.core.model.DownloadableFile;
import dynamo.core.model.DownloadableUtilsDAO;

@Path("file-list")
public class FileListService {
	
	private static final DownloadableUtilsDAO downloadableDAO = DAOManager.getInstance().getDAO( DownloadableUtilsDAO.class );
	
	@GET
	@Path("{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<DownloadableFile> getFilesForId( @PathParam("id") long id ) {
		return downloadableDAO.getAllFiles(id);
	}

	@DELETE
	public void delete(@QueryParam("path") String pathStr) {
		java.nio.file.Path path = Paths.get( pathStr );
		BackLogProcessor.getInstance().schedule( new DeleteFileTask(path), false );
	}
	
	@GET
	@Path("/download")
	public Response downloadFile( @QueryParam("path") String pathStr ) throws IOException {
		java.nio.file.Path path = Paths.get( pathStr );
		DownloadableFile file = downloadableDAO.getFile(path);

		String fileName = path.getFileName().toString();
		
		try (InputStream input = Files.newInputStream(path)) {
			return Response.ok(
					input, MediaType.APPLICATION_OCTET_STREAM)
					.header("Content-Length", file.getSize())
					.header("content-disposition","attachment; filename = " + fileName)
					.build();
		}
		
	}

}

@@ -71,24 +71,53 @@
 nputStream;%0A
+import java.io.OutputStream;%0A
 import java.
@@ -346,24 +346,68 @@
 QueryParam;%0A
+import javax.ws.rs.WebApplicationException;%0A
 import javax
@@ -462,16 +462,96 @@
 esponse;
+%0Aimport javax.ws.rs.core.StreamingOutput;%0A%0Aimport org.apache.commons.io.IOUtils;
 %0A%0Aimport
@@ -1600,16 +1600,19 @@
 g();%0A%09%09%0A
+%09%09%0A
 %09%09try (I
@@ -1660,16 +1660,217 @@
 ath)) %7B%0A
+%09%09%09StreamingOutput stream = new StreamingOutput() %7B%0A%09%09%09%09@Override%0A%09%09%09%09public void write(OutputStream output) throws IOException, WebApplicationException %7B%0A%09%09%09%09%09IOUtils.copy(input, output);%0A%09%09%09%09%7D%0A%09%09%09%7D;%0A
 %09%09%09retur
@@ -1887,19 +1887,21 @@
 .ok(
+ 
 %0A%09%09%09%09%09
-input
+stream
 , Me

Fix download