package com.apobates.forum.utils.fileupload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

/**
 * Servlet3 part实现
 * @author xiaofanku@live.cn
 * @since 20170419
 */
public class ServletPartUploadConnector extends AbstractUploadConnector{
    public ServletPartUploadConnector(UploadHandler handler) {
        super(handler);
    }
    /**
     * 
     * @param filePart 二进制流
     * @param uploadDir 保存的的目录
     * @param callFuntion 回调函数
     * @return
     * @throws IOException 
     */
    private String execute(Part filePart, File uploadDir, String callFuntion) throws IOException {
        String redata="-1";
        String originalFileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
        super.checkFileExtension(originalFileName);
        super.checkFileByteSize(filePart.getSize());
        //如果没有提供文件名使用原文件名
        //如果原文件名获取失败使用日期快照名
        String saveFileName=(getHandler().generateFileName()!=null)?getHandler().generateFileName():originalFileName;
        //开始保存文件
        OutputStream out = null;
        InputStream filecontent = null;
        try {
            out = new FileOutputStream(new File(uploadDir, saveFileName));
            filecontent = filePart.getInputStream();
            
            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            redata=getHandler().getResponse(saveFileName, callFuntion);
        } catch (FileNotFoundException fne) {
            getHandler().forceException(fne);
        } finally {
            if (null!=out) {
                out.close();
            }
            if (null!=filecontent) {
                filecontent.close();
            }
        }
        getHandler().otherProcess(uploadDir, saveFileName, callFuntion);
        return redata;
    }
    
    public String upload(UploadInitParamers params) throws IOException, ServletException{
        //保存的路径
        File uploadDir=new File(params.getFileSaveDir());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        HttpServletRequest request=params.getRequest();
        String callbackFun=request.getParameter(params.getCallbackFunctionName());
        
        return execute(request.getPart(params.getUploadFileInputName()), uploadDir, callbackFun);
    }
}
