package eu.dnetlib.server;

import eu.dnetlib.efg1914.authoring.managers.MediaManager;
import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@Service("GwtuploadServlet")
public class GwtUploadServlet extends UploadAction {

	MediaManager mediaManager;
	WebApplicationContext context;

	private static Logger log = Logger.getLogger("upload servlet: ");

	private static final long serialVersionUID = 1L;

	Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();
	/**
	 * Maintain a list with received files and their content types.
	 */
	Hashtable<String, File> receivedFiles = new Hashtable<String, File>();

	/**
	 * Override executeAction to save the received files in a custom place and
	 * delete this items from session.
	 */
	@Override
	public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {

		context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

		mediaManager = (MediaManager) context.getBean("mediaManager");
		
		String response = "";
		for (FileItem item : sessionFiles) {
			if (false == item.isFormField()) {
				try {
					String parameters = request.getParameter("source");
				 
					log.log(Level.INFO, "************* isThumb and size ***** " + parameters);
					String maxUploadSize = parameters.split("size=")[1];

					log.log(Level.INFO, "************* MAX SIZE " + maxUploadSize);
					int maxUploadSizeInt = Integer.parseInt(maxUploadSize);
					maxUploadSizeInt=maxUploadSizeInt*1024*1024;
					log.log(Level.INFO, "************* MAX SIZE " + maxUploadSizeInt);
					String isSource = parameters.split("size=")[0];
					log.log(Level.INFO, "************* isThumb ***** " + isSource);

					log.log(Level.INFO, "************* TYPE ***** " + item.getContentType());

					log.log(Level.INFO, "************* SIZE ***** " + item.getSize());
					if (item.getSize() <= maxUploadSizeInt) {
						 
						InputStream Stream = item.getInputStream();

						BufferedInputStream buff = new BufferedInputStream(Stream);

						if (isSource != null && isSource.equals("itemMini")) {
							ImageIO.setUseCache(false);
							BufferedImage sourceImage = ImageIO.read(buff);
							String mini;
							try {
								mini = mediaManager.saveMiniImage(item.getContentType(), sourceImage);
 							} catch (Exception e) {
								e.printStackTrace();
								mini = "ERROR";
							}
							response = mini + "_";

							String medium;
							try {
								medium = mediaManager.saveMediumImage(item.getContentType(), sourceImage);
 							} catch (Exception e) {
								e.printStackTrace();
								medium = "ERROR";
							}

							response += medium;
							buff.close();

						} else if (isSource != null && isSource.equals("itemSource")) {
							if (item.getContentType().contains("image")) {
								try {
									response = mediaManager.saveSourceMidiMini(item.getContentType(), buff);
									 
								} catch (Exception e) {
									e.printStackTrace();
									response = "ERROR";
								}
							} else {

								String source;
								try {
									source = mediaManager.saveMediaFile(item.getContentType(), buff);
									 
								} catch (Exception e) {
									e.printStackTrace();
									source = "ERROR";
								}

								receivedContentTypes.put(item.getFieldName(), item.getContentType());
								response += source;
							}

						} else if (isSource != null && isSource.equals("themeMini")) {
							ImageIO.setUseCache(false);
							BufferedImage sourceImage = ImageIO.read(buff);
							String mini;
							try {
								mini = mediaManager.saveMediumImage(item.getContentType(), sourceImage);
								 
							} catch (Exception e) {
								e.printStackTrace();
								mini = "ERROR";
							}
							response = mini;
							buff.close();
						} else {
							String t;
							try {
								t = mediaManager.saveMediaFile(item.getContentType(), buff);
								 
							} catch (Exception e) {
								e.printStackTrace();
								t = "ERROR";
							}

							receivedContentTypes.put(item.getFieldName(), item.getContentType());
							response = t;
							buff.close();
						}

					} else {
						response = "TOOBIG";
					}
				} catch (Exception e) {
					e.printStackTrace();
					// throw new UploadActionException(e);
				}
			}
		}

		removeSessionFileItems(request);

		// / Send your customized message to the client.
		System.out.println("SERVER RESPONSE............... " + response);
		return response;
	}
  	@Override
 	public void removeItem(HttpServletRequest request, FileItem item) throws UploadActionException {
		log.log(Level.INFO, "\n\n\n************* \n REMOVE \n *********** ***** \n\n\n\n" );

  		super.removeItem(request, item);
 	}
}
