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 {

	private Integer maxfilesize;
	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");

		maxfilesize = (Integer) context.getBean("maxfilesize");

		log.log(Level.INFO, "get image iterator");

		log.log(Level.INFO, "************* MAX SIZE " + maxfilesize);

		String response = "";

		for (FileItem item : sessionFiles) {
			if (false == item.isFormField()) {
				try {

					InputStream Stream = item.getInputStream();

					BufferedInputStream buff = new BufferedInputStream(Stream);

					String isThumb = request.getParameter("thumb");
					log.log(Level.INFO, "************* TYPE ***** " + item.getContentType());

					if (isThumb != null && isThumb.equals("true")) {
						ImageIO.setUseCache(false);
						BufferedImage sourceImage = ImageIO.read(buff);

						String mini = mediaManager.saveMiniImage(item.getContentType(), sourceImage);
						String medium = mediaManager.saveMediumImage(item.getContentType(), sourceImage);

						response = mini;

						response += "_" + medium;
						buff.close();

					} else if (isThumb != null && isThumb.equals("all")) {
						if (item.getContentType().contains("image")) {
							response = mediaManager.saveSourceMidiMini(item.getContentType(), buff);
						} else {
							String source = mediaManager.saveMediaFile(item.getContentType(), buff);
							receivedContentTypes.put(item.getFieldName(), item.getContentType());
							response += source;
						}

					} else if (isThumb != null && isThumb.equals("mini")) {
						ImageIO.setUseCache(false);
						BufferedImage sourceImage = ImageIO.read(buff);
						String mini = mediaManager.saveMiniImage(item.getContentType(), sourceImage);
						response = mini;
						buff.close();
					} else {

						String t = mediaManager.saveMediaFile(item.getContentType(), buff);

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

				} 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;
	}
}
