package org.gcube.portlets.user.reportgenerator.server.servlet;




import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.application.framework.core.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <code> ImagesUploadServlet </code> class is the server code delgated to receinve the byte stream and store i
 *
 * @author Massimiliano Assante, ISTI-CNR - massimiliano.assante@isti.cnr.it
 * @version October 2008 (0.2) 
 */

public class ImagesUploadServlet extends HttpServlet {
	

	private static final Logger _log = LoggerFactory.getLogger(ImagesUploadServlet.class);
	
	final String returnOKMessage = "OK";

	private static final long serialVersionUID = 1L;

	private String currentUser;

	private String currentScope;

	/**
	 * 
	 * @param message the msg
	 */
	public static void logger (String message) {
		System.out.println("***" + message);
	}
	/**
	 * return the user template folder
	 * @param templateName
	 * @param currentDL . 
	 * @param currentUser .
	 * @return .
	 */
	private String getTemplateFolder(String currentDL, String currentUser) {
		_log.debug("getTemplateFolder Method called");
		//		platform indipendent slash
		String sl = File.separator;		
		//e.g. /home/massi/workspace/templategen/tomcat/webapps/ROOT
		String path = System.getenv("CATALINA_HOME");
		path +=	sl + "webapps" + sl +"usersArea" + sl + currentDL +
		sl + "templates" + sl + currentUser + sl ;
		_log.debug("Returning Path= " + path);
		return path;

	}
	/**
	 *  file upload handler
	 *  @param request .
	 *  @param response .
	 *  @throws ServletException .
	 *  @throws IOException .
	 */

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {

//		logger("ImagesUploadServlet received:");
//	
//		currentUser = getUsername(request);
//		currentScope = getVreName(request);
//	
//		String currTemplateName = request.getParameter("currTemplateName"); 
//	
//		logger("currentUser: "+currentUser);
//		logger("currentVRE: "+currentScope);
//		logger("currTemplateName: "+currTemplateName);
//		logger("CALLING :getTemplateFolder ");
//		logger("RETURNED :getTemplateFolder ");
//		//platform indipendent slash
//		String sl = File.separator;		
//		String startDirectory = getTemplateFolder(currentScope, currentUser); //e.g. /home/massi/workspace/templategen/tomcat/webapps/ROOT
//		int lastSlash = startDirectory.lastIndexOf(sl);
//		startDirectory = startDirectory.substring(0, lastSlash);
//		
//		startDirectory +=	sl +  "CURRENT_OPEN" + sl  + "images";
//
//		logger("RETURNED : " + startDirectory);
//		logger("WRITING... :");
//		
//		String fileName = "";
//		PrintWriter out = response.getWriter();
//
//		if (!ServletFileUpload.isMultipartContent(request))
//			return;
//
//		FileItemFactory factory = new DiskFileItemFactory();
//		ServletFileUpload upload = new ServletFileUpload(factory);
//
//		List items = null;
//		try {
//			items = upload.parseRequest(request);
//		}
//		catch (FileUploadException e) {
//			e.printStackTrace();
//			return;
//		}
//		File uploadedFile = null;
//		for (Iterator i = items.iterator(); i.hasNext();) {
//			FileItem item = (FileItem) i.next();
//
//			if (item.isFormField()) 
//				continue;
//			fileName = item.getName();
//			if (fileName != null && fileName.compareTo("")!=0) {
//				fileName = FilenameUtils.getName(fileName);
//
//				uploadedFile = new File(startDirectory + File.separator + fileName);
//				try {
//					if(!uploadedFile.exists()){
//						File toCreate = new File(startDirectory);
//						boolean success = toCreate.mkdirs();
//						if (success)
//							Logger.debug("New file \"" + uploadedFile + "\" has been created ");
//					}
//					item.write(uploadedFile);
//				} 
//				catch (Exception e) {	e.printStackTrace(); }
//
//			}
//		}
//
//		out.print(returnOKMessage);
//		out.close();

	} //end service

	/**
	 * 
	 * @param httpServletRequest .
	 * @return .
	 */
	public String getUsername(HttpServletRequest httpServletRequest) {
		
		HttpSession session = httpServletRequest.getSession();
		String user = (String) session.getAttribute("username");
		if(session.getAttribute("username")== null)
		{
			user = "massi";
			logger("D4ScienceSession user NULL set to: " + user);
		}
		logger("D4ScienceSession user: " + user);

		ASLSession d4session = SessionManager.getInstance().getASLSession(session.getId(), user);
		d4session.setAttribute("username", user);
		return user;
	}

	/**
	 * @param httpServletRequest .
	 * @return the shared session
	 */
	public String getVreName(HttpServletRequest httpServletRequest) {
		HttpSession session = httpServletRequest.getSession();

		ASLSession d4session = SessionManager.getInstance().getASLSession(session.getId(), getUsername(httpServletRequest));
		String scope = d4session.getScopeName();
		//need to remove the initial / of the scope
		if (scope.charAt(0) == '/')
			scope = scope.substring(1, scope.length());
		logger("ImagesUploadServlet SCOPE: " + scope);
		//String scope = "gcube/devsec";
		return scope;
	}
}
