package com.apobates.forum.bucket.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.fileupload.UploadInitParamers;
import com.apobates.forum.utils.fileupload.ckeditor.CKEditorHightHandler;
import com.apobates.forum.utils.fileupload.fileinput.BootStrapFileInputResponse;
/**
 * Bootstrap FileInput的上传
 * {@link https://plugins.krajee.com/file-input}
 * @author xiaofanku@live.cn
 * @since 20191101
 */
public class UploadFileinputServlet extends HttpServlet{
	private static final long serialVersionUID = 2039243498775491760L;
	private String uploadImageDirectName; 
	private String siteDomain; 
	private long uploadMaxByte;
	private final static Logger logger = LoggerFactory.getLogger(UploadFileinputServlet.class);
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		//子目录
		String childDirect = DateTimeUtils.getYMD();
		// 项目路径
		final String realPath = request.getServletContext().getRealPath("/") + File.separator + uploadImageDirectName + File.separator + childDirect;
		// 前台访问路径
		final String frontVisitPath = siteDomain + uploadImageDirectName + "/"+childDirect+"/";
		UploadInitParamers cip = new UploadInitParamers() {
			@Override
			public String getFileSaveDir() {
				return realPath;
			}

			@Override
			public String getCallbackFunctionName() {
				// 没有回调函数
				return null;
			}

			@Override
			public String getUploadFileInputName() {
				return "file";
			}

			@Override
			public HttpServletRequest getRequest() {
				return request;
			}
		};
		String outResult=null; 
		try {
			ServletFileUploadConnector connector = new ServletFileUploadConnector(new CKEditorHightHandler(frontVisitPath, uploadMaxByte));
			String responsebody = connector.upload(cip);
			outResult = new BootStrapFileInputResponse(request.getParameter("id"), responsebody).toJson();
		} catch (Exception e) {
			String errorMesg = e.getMessage();
			logger.info("[UFS]异常消息: "+errorMesg);
			if (logger.isDebugEnabled()) {
				logger.debug(errorMesg, e);
			}
			outResult = BootStrapFileInputResponse.error(errorMesg);
		}
		logger.info("[UFS]输出响应: "+outResult);
		//
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		try(PrintWriter out = response.getWriter()){
			out.write(outResult);
			out.flush();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		try (PrintWriter out = resp.getWriter()) {
			out.println("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Access Denied</title></head><body><p>暂不支持浏览功能</p></body></html>");
			out.flush();
		}
	}
	
	/**
	 * 获得初始化值
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.siteDomain = config.getInitParameter("siteDomain"); //站点URL, http://xx.com
		this.uploadImageDirectName = config.getInitParameter("uploadImageDirectName"); //图片保存的目录
		this.uploadMaxByte = 5242880; //5M
		try{
			uploadMaxByte=Long.valueOf(config.getInitParameter("uploadMaxByte")); //multipart-config.max-request-size
		}catch(NullPointerException | NumberFormatException e){}
	}
}
