package org.openforis.collect.web.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.openforis.collect.io.metadata.collectearth.balloon.CollectEarthBalloonGenerator;
import org.openforis.collect.manager.RecordManager;
import org.openforis.collect.manager.SurveyManager;
import org.openforis.collect.metamodel.SurveyViewGenerator;
import org.openforis.collect.metamodel.SurveyViewGenerator.SurveyView;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.SurveySummary;
import org.openforis.idm.metamodel.EntityDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * @author S. Ricci
 *
 */
@Controller
public class SurveyController extends BasicController {

	private static final String EDIT_SURVEY_VIEW = "editSurvey";

	@Autowired
	private RecordManager recordManager;
	@Autowired
	private SurveyManager surveyManager;

	@RequestMapping(value = "/surveys/summaries.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody
	List<SurveySummary> loadSummaries(
			@RequestParam(required=false) boolean includeTemporary,
			@RequestParam(required=false) boolean includeRecordIds) throws Exception {
		String language = Locale.ENGLISH.getLanguage();
		if (includeTemporary) {
			return surveyManager.loadCombinedSummaries(language, true);
		} else {
			return surveyManager.getSurveySummaries(language);
		}
	}

	@RequestMapping(value = "/surveys/{id}.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody
	SurveyView loadSurvey(@PathVariable int id) throws Exception {
		CollectSurvey survey = surveyManager.getOrLoadSurveyById(id);
		SurveyViewGenerator viewGenerator = new SurveyViewGenerator(Locale.ENGLISH);
		SurveyView view = viewGenerator.generateView(survey);
		return view;
	}
	
	protected List<Integer> getRecordIds(SurveySummary s) {
		List<Integer> recordIds = new ArrayList<Integer>();
		CollectSurvey survey = surveyManager.getById(s.getId());
		List<EntityDefinition> rootEntities = survey.getSchema().getRootEntityDefinitions();
		EntityDefinition rootEntity = rootEntities.get(0);
		String rootEntityName = rootEntity.getName();
		List<CollectRecord> recordSummaries = recordManager.loadSummaries(survey, rootEntityName);
		for (CollectRecord r : recordSummaries) {
			recordIds.add(r.getId());
		}
		return recordIds;
	}
	
	@RequestMapping(value = "/surveys/temp/{surveyId}/edit.htm", method = RequestMethod.GET)
	public ModelAndView editTemp(@PathVariable("surveyId") Integer surveyId, Model model) {
		model.addAttribute("temp_id", surveyId);
		return new ModelAndView(EDIT_SURVEY_VIEW);
	}
	
	@RequestMapping(value = "/surveys/{surveyId}/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@PathVariable("surveyId") Integer surveyId, Model model) {
		model.addAttribute("id", surveyId);
		return new ModelAndView(EDIT_SURVEY_VIEW);
	}
	
	@RequestMapping(value = "/collectearthpreview.html", method = RequestMethod.GET, produces=MediaType.TEXT_HTML_VALUE)
	public void showCollectEarthBalloonPreview(HttpServletResponse response, 
			@RequestParam("surveyId") Integer surveyId, @RequestParam("lang") String languageCode)  {
		PrintWriter writer = null;
		try {
			CollectSurvey survey = surveyManager.loadSurvey(surveyId);
			CollectEarthBalloonGenerator generator = new CollectEarthBalloonGenerator(survey, languageCode);
			String html = generator.generateHTML();
			writer = new PrintWriter(response.getOutputStream());
			writer.print(html);
			writer.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(writer);
		}
	}
}

@@ -38,24 +38,53 @@
 troller;%0D%0A%0D%0A
+import java.io.IOException;%0D%0A
 import java.
@@ -3828,44 +3828,8 @@
 .GET
-, produces=MediaType.TEXT_HTML_VALUE
 )%0D%0A%09
@@ -3997,52 +3997,31 @@
 de) 
- %7B%0D%0A%09%09PrintWriter writer = null;%0D%0A%09%09try
+throws IOException 
  %7B%0D%0A
-%09
 %09%09Co
@@ -4078,17 +4078,16 @@
 eyId);%0D%0A
-%09
 %09%09Collec
@@ -4178,17 +4178,16 @@
 Code);%0D%0A
-%09
 %09%09String
@@ -4217,24 +4217,264 @@
 ateHTML();%0D%0A
+%09%09writeHtmlToResponse(response, html);%0D%0A%09%7D%0D%0A%0D%0A%09private void writeHtmlToResponse(HttpServletResponse response, String html) throws IOException %7B%0D%0A%09%09PrintWriter writer = null;%0D%0A%09%09try %7B%0D%0A%09%09%09response.setContentType(MediaType.TEXT_HTML_VALUE);%0D%0A
 %09%09%09writer = 

Fix problem showing Collect Earth preview