package adios.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.google.gson.Gson;
import adios.model.Ingredient4Recipe;
import adios.model.Recipe;
import adios.model.Tag;
import adios.model.User;
import adios.service.IngredientService;
import adios.service.RecipeService;
import adios.service.TagService;
import adios.service.UserService;
@Controller
public class RecipeController {
protected final Log Log = LogFactory.getLog(getClass());
private static final String loginUser = "LOGGEDIN_USER";
@Autowired
private TagService tagService;
@Autowired
private RecipeService recipeService;
@Autowired
private IngredientService ingredientService;
@Autowired
private UserService userService;
/**
* returns a recipe for a given id
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/receta/{recipeId}.html", method = RequestMethod.GET)
public ModelAndView getRecipe(@PathVariable int recipeId,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/receta/{recipeId}.html");
Recipe r=new Recipe();
r.setRecipeId(recipeId);
Ingredient4Recipe i4r = new Ingredient4Recipe();
i4r.setRecipeId(r.getRecipeId());
ArrayList<Ingredient4Recipe> i4rList = ingredientService.getIngredientsForRecipe(i4r);
ModelAndView view = new ModelAndView("html/recipePage");
view.addObject("recipe", recipeService.getRecipe(recipeId));
view.addObject("tags", tagService.getTagForRecipe(r));
view.addObject("ingredients", i4rList);
return view;
}
/**
* returns the recipes added by the user for to the cart
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/user/receta/compra/lista.html", method = RequestMethod.GET)
public ModelAndView returnShoppingList(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/user/receta/compra/lista.html");
ModelAndView view = new ModelAndView("html/mainTemplate");
User u = (User)request.getSession().getAttribute(loginUser);
u = userService.getUserForMail(u);
ArrayList<Recipe> rList = new ArrayList<Recipe>();
Map<Integer, Recipe>recipesCartMap = u.getCartRecipes();
final Hashtable<String, Ingredient4Recipe> ingHT;
if (recipesCartMap!= null){
ingHT = new Hashtable<String, Ingredient4Recipe>(); ;
Set<Integer> recipesIdSet = recipesCartMap.keySet();
Iterator<Integer> recipesIdIter = recipesIdSet.iterator();
while(recipesIdIter.hasNext()){
Integer i =recipesIdIter.next();
Recipe r = recipeService.getRecipe(i.intValue());
rList.add(r);
Ingredient4Recipe i4r = new Ingredient4Recipe();
i4r.setRecipeId(r.getRecipeId());
ArrayList<Ingredient4Recipe> i4rList = ingredientService.getIngredientsForRecipe(i4r);
Iterator<Ingredient4Recipe> i4rIter = i4rList.iterator();
while (i4rIter.hasNext()){
i4r = i4rIter.next();
if(ingHT.containsKey(i4r.getName())){
Ingredient4Recipe i4rTmp = (Ingredient4Recipe) ingHT.get(i4r.getName());
i4rTmp.setQuantity(i4rTmp.getQuantity()+i4r.getQuantity());
ingHT.put(i4rTmp.getName(), i4rTmp);
}else{
ingHT.put(i4r.getName(), i4r);
}
}
}
view.addObject("ingredients",ingHT);
}
view.addObject("recipeList", rList);
return view;
}
@RequestMapping(value="/user/receta/compra/{recipeId}.html", method = RequestMethod.POST)
public void addToShoppingList(@PathVariable int recipeId,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/receta/compra/{recipeId}.html");
User u = (User)request.getSession().getAttribute(loginUser);
u = userService.getUserForMail(u);
Integer i = Integer.valueOf(recipeId);
HashMap<Integer, Recipe> cartMap = u.getCartRecipes();
if(cartMap== null){
cartMap = new HashMap<Integer, Recipe>();
}
if(!cartMap.containsKey(i)){
cartMap.put(i, null);
u.setCartRecipes(cartMap);
u = userService.updateUser(u);
request.getSession().setAttribute(loginUser,u);
}
}
/**
* add a racipe to the favorites of a user
* @param recipeId
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/user/receta/favorita/{recipeId}.html", method = RequestMethod.POST)
public void addRecipeToFavorite(@PathVariable int recipeId,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/receta/favorita/{recipeId}.html");
User u = (User)request.getSession().getAttribute(loginUser);
u = userService.getUserForMail(u);
Integer i = Integer.valueOf(recipeId);
HashMap<Integer, Recipe> favsMap = u.getFavoriteRecipes();
if(favsMap== null){
favsMap = new HashMap<Integer, Recipe>();
}
if(!favsMap.containsKey(i)){
favsMap.put(i, null);
u.setFavoriteRecipes(favsMap);
u = userService.updateUser(u);
request.getSession().setAttribute(loginUser,u);
}
}
/**
* returns all the favorites (recipes) for a user
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/user/recetas/favoritas.html", method = RequestMethod.GET)
public ModelAndView returnRecipeToFavorite(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/user/recetas/favoritas.html");
User u = (User)request.getSession().getAttribute(loginUser);
u = userService.getUserForMail(u);
ArrayList<Recipe> rList = new ArrayList<Recipe>();
Map<Integer, Recipe>recipesFavsMap = u.getFavoriteRecipes();
if (recipesFavsMap!= null){
Set<Integer> recipesIdSet = recipesFavsMap.keySet();
Iterator<Integer> recipesIdIter = recipesIdSet.iterator();
while(recipesIdIter.hasNext()){
Integer i =recipesIdIter.next();
Recipe r = recipeService.getRecipe(i.intValue());
rList.add(r);
}
}
ModelAndView view = new ModelAndView("html/mainTemplate");
view.addObject("recipeList", rList);
return view;
}
/**
* returns the recipes for logged user
* @param recipeId
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/user/receta/lasRecetas.html", method = RequestMethod.GET)
public ModelAndView userRecipe(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/user/receta/lasRecetas.html");
User u = (User)request.getSession().getAttribute(loginUser);
ArrayList<Recipe> rList = null;
ModelAndView view = null;
if(u!=null){
view = new ModelAndView("html/userRecipes");
rList = recipeService.getRecipeForUserId(u.getUserId());
}else{
rList = recipeService.getLastRecipes(5);
view =new ModelAndView("html/mainTemplate");
}
view.addObject("recipeList", rList);
return view;
}
@RequestMapping(value="/user/receta//editar/{recipeId}.html", method = RequestMethod.GET)
public ModelAndView eidrRecipe(@PathVariable int recipeId,HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/receta/editar/{recipeId}.html");
Recipe r = recipeService.getRecipe(recipeId);
Ingredient4Recipe i4r = new Ingredient4Recipe();
i4r.setRecipeId(r.getRecipeId());
ArrayList<Ingredient4Recipe> i4rList = ingredientService.getIngredientsForRecipe(i4r);
ModelAndView view = new ModelAndView("html/recipePage");
view.addObject("recipe", recipeService.getRecipe(recipeId));
view.addObject("tags", tagService.getTagForRecipe(r));
view.addObject("ingredients", i4rList);
return view;
}
/**
* returns the empty page where we can add a recipe
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/user/anadirReceta.html", method = RequestMethod.GET)
public ModelAndView signUpGetHandleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("/anadirReceta/{userId}.html");
ModelAndView view = new ModelAndView("html/addRecipe");
return view;
}
/**
* post the recipe (description name externalMedia image)
* @param userId
* @param request
* @param response
* @return recipeId
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/user/anadirReceta/nueva.html", method = RequestMethod.POST)
public String createRecipe(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("user/anadirReceta/{userId}.html");
User u = (User)request.getSession().getAttribute(loginUser);
int userId = u.getUserId();
String name = request.getParameter("name");
String desc = request.getParameter("desc");
Recipe r = new Recipe();
r.setUserId(userId);
r.setName(name);
r.setDescription(desc);
r = recipeService.createRecipe(r);
request.getSession().removeAttribute("recipe");
request.getSession().setAttribute("recipe", r);
return String.valueOf(r.getRecipeId());
}
/**
* add step to recipe
* @param step
* @param recipeId
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="/user/anadirReceta/nueva/instrucciones.html", method = RequestMethod.POST)
public String addStepToRecipe( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("user/anadirReceta/{step}.html");
String stepsJsArray = request.getParameter("stepsJsArray");
try{
Recipe r = (Recipe)request.getSession().getAttribute("recipe");
Gson gson = new Gson();
String[] stepsArray = gson.fromJson("["+stepsJsArray+"]", String[].class);
ArrayList<String> steps = new ArrayList<String>(Arrays.asList(stepsArray));
r.setInstructions(steps);
recipeService.updateRecipe(r);
request.getSession().setAttribute("recipe", r);
}catch(Exception e){
return "false";
}
return "true";
}
@RequestMapping(value="/user/anadirReceta/nueva/tag.html", method = RequestMethod.POST)
public String addTagToRecipe( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("user/anadirReceta/{step}.html");
String tag = request.getParameter("tag");
try{
Recipe r = (Recipe)request.getSession().getAttribute("recipe");
Tag t =new Tag();
t.setName(tag);
t.setRecipeId(r.getRecipeId());
tagService.addTag(t);
request.getSession().setAttribute("recipe", r);
}catch(Exception e){
return "false";
}
return "true";
}
@RequestMapping(value="/user/anadirReceta/nueva/ingrediente.html", method = RequestMethod.POST)
public String addIngredienteToRecipe( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Log.info("user/anadirReceta/{step}.html");
String ingName = request.getParameter("name");
String ingUnit = request.getParameter("unit");
String ingQuantity = request.getParameter("quantity");
try{
Recipe r = (Recipe)request.getSession().getAttribute("recipe");
Ingredient4Recipe i = new Ingredient4Recipe();
i.setQuantity(Integer.parseInt(ingQuantity));
i.setName(ingName);
i.setRecipeId(r.getRecipeId());
i.setUnit(ingUnit);
ingredientService.addIngredient(i);
request.getSession().setAttribute("recipe", r);
}catch(Exception e){
return "false";
}
return "true";
}
/**
* post the image for a recipe
* @param multipartFile
* @param response
* @throws Exception
*/
@RequestMapping(method = RequestMethod.POST, value = "/user/recipieImage.html",headers={"content-type=multipart/form-data"})
public void onSubmit( @RequestParam("file") MultipartFile multipartFile,
final HttpServletResponse response)
throws Exception
{
Log.info("/recipieImage.html");
String fileName="";
if(multipartFile!=null)
{
fileName = multipartFile.getOriginalFilename();
}
//file inputstream can be accessed as multipartFile.getInputStream()
String resultCode = "0";
final String responseHTML = "<html><head></head><body><textarea>" + resultCode + "</textarea></body></html>";
response.setContentType("text/html");
final OutputStream responseStream = response.getOutputStream();
responseStream.write(responseHTML.getBytes());
responseStream.write("\r\n".getBytes());
responseStream.close();
}
// http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
// @ResourceMapping("ajaxTest")
// public void ajaxHandler(ResourceRequest request, ResourceResponse response)
// throws IOException {
// OutputStream outStream = response.getPortletOutputStream();
// StringBuffer buffer = new StringBuffer();
//
// Map<String, String> testMap = new HashMap<String, String>();
// testMap.put("foo", "bar");
//
// String test = new JSONObject(testMap).toString();
// buffer.append(test);
//
// outStream.write(buffer.toString().getBytes());
// }
// In "view.jsp":
//
// <portlet:resourceURL var="ajaxtest" id="ajaxTest"/>
//
// <script type="text/javascript">
// $.get('<%= ajaxtest %>', function(response) {
// var json = eval('(' + response + ')');
// });
// </script>
}