package org.yacos.web.author.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;

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.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import org.yacos.core.article.*;
import org.yacos.web.author.form.*;

public class SArticleController extends SimpleFormController {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	private IArticleManager articleManager;

	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
	throws ServletException, IllegalStateException {

		String title = ((FormSubmission) command).getTitle();
		String theme = ((FormSubmission) command).getTheme();
		String mainauthor = ((FormSubmission) command).getMainauthor();
		//String secondaryauthor = ((FormSubmission) command).getSecondaryauthor();
		//TODO : get secondary author working
		List<String> liste = ((FormSubmission) command).getListe();

		String nomFile="";

		try {
			MultipartFile file = ((FormSubmission) command).getFile();
			if (file == null) {

			}
			else {

				byte b[] = file.getBytes();
				File file2 = new File(file.getOriginalFilename()); 
				// TODO mettre le bon path ici

				FileOutputStream fos = new FileOutputStream(file2);

				URL testURL = file2.toURL();
				nomFile = testURL.toString();

				fos.write(b);
				fos.close();
			}
		}
		catch (FileNotFoundException e) {
			System.out.println(e);
		} catch (IOException e) {
			System.out.println(e);
		}

		Article a = new Article(0, title, theme, nomFile, mainauthor, liste, 1);
		articleManager.addArticle(a);

		return new ModelAndView(new RedirectView(getSuccessView()));
	}

	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
		FormSubmission myArticle = new FormSubmission();
		myArticle.setTitle("");
		myArticle.setTheme("");
		myArticle.setMainauthor("");
		myArticle.setSecondaryauthor("");
		return myArticle;
	}

	public IArticleManager getArticleManager() {
		return articleManager;
	}

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

}