package net.roseindia.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.roseindia.model.Article;
import net.roseindia.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/articles")
public class ArticleController {

	@Autowired
	private ArticleService articleService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView listArticles(HttpServletRequest request ) {
		Map<String, Object> model = new HashMap<String, Object>();
		if(request.getParameter("articleId")!=null && (!(request.getParameter("articleId")).equals(""))){
			 Long articleId=Long.parseLong(request.getParameter("articleId"));
			 model.put("articles",  articleService.getArticleByArticleId(articleId));
		  }else{
			  model.put("articles",  articleService.listArticles());  
		  }
		return new ModelAndView("articlesList", model);
	}
	
	@RequestMapping(value = "/searcharticle", method = RequestMethod.GET)
	public ModelAndView addArticle(@ModelAttribute("article") Article article) {
		return new ModelAndView("searcharticle");
	}
	
	@RequestMapping(value = "/searcharticle", method = RequestMethod.POST)
	public ModelAndView saveArticle(@ModelAttribute(" article") Article  article) {		 
		
		return new ModelAndView("redirect:/articles.html?articleId="+article.getArticleId());
	 }

}