package org.yacos.web.author.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;
import org.yacos.core.article.Article;
import org.yacos.core.article.IArticleManager;
import org.yacos.core.forum.IMessageManager;
import org.yacos.core.users.IUserManager;

public class ArticleDeleteController implements Controller {
	private IMessageManager messageManager;
	
	private IArticleManager articleManager;
	public IArticleManager getArticleManager() {
		return articleManager;
	}

	public void setArticleManager(IArticleManager articleManager) {
		this.articleManager = articleManager;
	}

	private IUserManager userManager;
	public IUserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}

	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			Integer articleId = Integer.parseInt(request.getParameter("articleId"));
			Article article = articleManager.getArticle(articleId);

			// FIXME : v�rifier si le gars a le droit de suppr ou pas

			if(article == null){
				return new ModelAndView(new RedirectView("404error.htm"));
			}
	
			if(!articleManager.getPreferencesForArticle(articleId).isEmpty()
					|| !userManager.getPCMemberForArticle(articleId).isEmpty()
					|| messageManager.getMessagesForArticle(articleId).isEmpty()){
					return new ModelAndView(new RedirectView("manageArticle.htm?delete=ko"));
			}
			articleManager.removeArticle(articleId);

		} 
		catch(NumberFormatException e) {
			throw new ModelAndViewDefiningException(new ModelAndView("404error"));
		}

		return new ModelAndView(new RedirectView("manageArticle.htm?delete=ok"));
	}

	public IMessageManager getMessageManager() {
		return messageManager;
	}

	public void setMessageManager(IMessageManager messageManager) {
		this.messageManager = messageManager;
	}

	
}