package uk.ac.ebi.quickgo.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import uk.ac.ebi.quickgo.service.annotation.AnnotationService;
import uk.ac.ebi.quickgo.service.annotation.parameter.AnnotationParameters;
import uk.ac.ebi.quickgo.web.util.FileService;
import uk.ac.ebi.quickgo.web.util.annotation.AnnotationColumn;
import uk.ac.ebi.quickgo.web.util.annotation.AppliedFilterSet;

/**
 * Controller for the download of annotations
 * @author cbonill
 *
 */

@Controller
public class DownloadController {	
	
	@Autowired
	AnnotationService annotationService;
	
	@Autowired
	FileService fileService;
	
	private static final Logger logger = Logger.getLogger(DownloadController.class);	
	
	@RequestMapping(value = { "/", "annotation" }, method = {RequestMethod.POST, RequestMethod.GET }, params = { "format" })
	public void download(
			@RequestParam(value = "format", defaultValue = "tab") String format,
			HttpSession session, HttpServletResponse httpServletResponse) {

		// Get columns to display		
		AnnotationColumn[] visibleColumns = (AnnotationColumn[]) session.getAttribute("visibleAnnotationsColumns");
		
		// Get applied filters and convert them into Solr query
		AnnotationParameters annotationParameters = new AnnotationParameters();		
		AppliedFilterSet appliedFilterSet = (AppliedFilterSet) session.getAttribute("appliedFilters");
		annotationParameters.setParameters(appliedFilterSet.getParameters());
		String query = annotationParameters.toSolrQuery();

		// Get total number annotations
		long totalAnnotations = annotationService.getTotalNumberAnnotations(query);
		int numResults = 10000; //TODO Add parameter in request to specify limit
		
		// Check file format
		StringBuffer sb = null;
		try {				
			switch (FileService.FILE_FORMAT.valueOf(format.toUpperCase())) {
			case TSV:
				sb = fileService.generateTSVfile(FileService.FILE_FORMAT.TSV, "", query, totalAnnotations, visibleColumns, numResults);
				break;
			case FASTA:
				sb = fileService.generateFastafile(query, totalAnnotations, numResults);
				break;
			case GAF:										
				sb = fileService.generateGAFFile(query, totalAnnotations, numResults);
				break;
			case GPAD:
				sb = fileService.generateGPADFile(query, totalAnnotations, numResults);
				break;
			case PROTEINLIST:
				sb = fileService.generateProteinListFile(query, totalAnnotations, numResults);
				break;
			case GENE2GO:
				sb = fileService.generateGene2GoFile(query, totalAnnotations, 10000);
				break;
			}
			InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
			IOUtils.copy(in, httpServletResponse.getOutputStream());
			
			// Set response header and content
			httpServletResponse.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
			httpServletResponse.setHeader("Content-Disposition","attachment; filename=annotations." + format);
			httpServletResponse.setContentLength(sb.length());
			
			httpServletResponse.flushBuffer();		
		} catch (IOException e) {
			logger.error(e.getMessage());
		}		
	}
}
@@ -1061,19 +1061,17 @@
 roller %7B
-%09%0A%09
+%0A
 %0A%09@Autow
@@ -1113,18 +1113,17 @@
 ervice;%0A
-%09
 %0A
+
 %09@Autowi
@@ -1152,17 +1152,16 @@
 ervice;%0A
-%09
 %0A%09privat
@@ -1234,19 +1234,17 @@
 .class);
-%09%0A%09
+%0A
 %0A%09@Reque
@@ -1548,18 +1548,16 @@
  display
-%09%09
 %0A%09%09Annot
@@ -1659,19 +1659,17 @@
 umns%22);%0A
-%09%09
 %0A
+
 %09%09// Get
@@ -1791,18 +1791,16 @@
 eters();
-%09%09
 %0A%09%09Appli
@@ -2202,19 +2202,17 @@
 y limit%0A
-%09%09
 %0A
+
 %09%09// Che
@@ -2259,20 +2259,16 @@
 %0A%09%09try %7B
-%09%09%09%09
 %0A%09%09%09swit
@@ -2595,18 +2595,8 @@
 GAF:
-%09%09%09%09%09%09%09%09%09%09
 %0A%09%09%09
@@ -2996,16 +2996,117 @@
 %09break;%0A
+%09%09%09case JSON:%0A%09%09%09%09sb = fileService.generateJsonFile(query, totalAnnotations, numResults);%0A%09%09%09%09break;%0A
 %09%09%09%7D%0A%09%09%09
@@ -3241,20 +3241,17 @@
 eam());%0A
-%09%09%09
 %0A
+
 %09%09%09// Se
@@ -3517,19 +3517,16 @@
 gth());%0A
-%09%09%09
 %0A%09%09%09http
@@ -3555,18 +3555,16 @@
 uffer();
-%09%09
 %0A%09%09%7D cat
@@ -3624,11 +3624,10 @@
 %0A%09%09%7D
-%09%09
 %0A%09%7D%0A
-
 %7D
+%0A

Add json response.