package com.apobates.forum.bucket.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apobates.forum.utils.fileupload.ApacheFileUploadConnector;
import com.apobates.forum.utils.fileupload.UploadHandler;
import com.apobates.forum.utils.fileupload.UploadInitParamers;
/**
 * 使用ASF file upload上传
 * 
 * @author xiaofanku
 * @since 20191027
 */
public class ServletFileUploadConnector extends ApacheFileUploadConnector {
	private final static Logger logger = LoggerFactory.getLogger(ServletFileUploadConnector.class);

	public ServletFileUploadConnector(UploadHandler handler) {
		super(handler);
	}

	public String upload(UploadInitParamers params) throws IOException, ServletException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);

		logger.info("[SFUC]allow bytes: " + getHandler().allowMaxBytes());
		sfu.setSizeMax(getHandler().allowMaxBytes());
		
		try {
			List<FileItem> data = sfu.parseParameterMap(params.getRequest()).get(params.getUploadFileInputName());
			if (null==data || data.isEmpty()) {
				throw new IOException("不存在可供使用的多字节流");
			}
			// 保存的路径
			File uploadDir = new File(params.getFileSaveDir());
			if (!uploadDir.exists()) {
				uploadDir.mkdirs();
			}
			String callbackFun = params.getCallbackFunctionName();
			return execute(data.get(0), uploadDir, callbackFun);
		} catch (FileUploadBase.SizeLimitExceededException e){
			if (logger.isDebugEnabled()) {
				logger.debug("[SFUC]SizeLimitExceeded Exception: " + e.getMessage());
			}
			throw new IOException("最大允许上传的容量: "+getHandler().allowMaxBytes()+"字节(Byte)");
		} catch (FileUploadException e) {
			if (logger.isDebugEnabled()) {
				logger.debug("[SFUC]FileUploadException: " + e.getMessage());
			}
			throw new IOException(e.getMessage());
		}
	}
}
