//	Contour - Android drawing teacher application
//	Copyright (C) 2014  Johannes Riedmann
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//	
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//	
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.j0h1.contour.admin.server;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;
import gwtupload.shared.UConsts;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;

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

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;

/**
 * Service implementation that handles image uploads.
 * @author Johannes Riedmann
 *
 */
public class FileUploadServiceImpl extends UploadAction {

	private static final long serialVersionUID = 1L;

	Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();
	Hashtable<String, String> receivedFiles = new Hashtable<String, String>();
	
	@Override
	public String executeAction(HttpServletRequest request,
			List<FileItem> sessionFiles) throws UploadActionException {
		String response = "";
		for (FileItem item : sessionFiles) {
			if (item.isFormField() == false) {
				try {					
					// base64 encoding image data
					byte[] base64Bytes = Base64.encodeBase64(item.get());
					String encodedImage = new String(base64Bytes);

					receivedFiles.put(item.getFieldName(), encodedImage);
					receivedContentTypes.put(item.getFieldName(),
							item.getContentType());
					
					response = "";
				} catch (Exception ex) {
					// do nothing
				}
			}
		}
		// remove files from session because we have a copy of them
		removeSessionFileItems(request);

		return response;
	}

	/**
	 * Get the content of an uploaded file.
	 */
	@Override
	public void getUploadedFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String fieldName = request.getParameter(UConsts.PARAM_SHOW);
		String s = receivedFiles.get(fieldName);
		if (s != null) {
			response.setContentType(receivedContentTypes.get(fieldName));
			ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
			copyFromInputStreamToOutputStream(is, response.getOutputStream());
		} else {
			renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
		}
	}

}
