package requestHandlers;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class uploadFile implements RequestHandler{
	private final int MAXFILESIZE = 100 * 1024 * 1024;
	private final int SIZETHRESHOLD = 4096;
	private final String saveDir = "";
	@Override
	public void processRequest(Object user, HttpServletRequest req,
			HttpServletResponse res, Object[] services, Object log)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = res.getWriter();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(SIZETHRESHOLD);
		ServletFileUpload upload = new ServletFileUpload(factory);
		String rid = "-1";
		String uid = "-1";
		String type = "";
		HttpServlet servlet = (HttpServlet)user;
		try
		{
			List<FileItem> fileItems = upload.parseRequest(req);
			Iterator<FileItem> iter = fileItems.iterator();
			while(iter.hasNext())
			{
				FileItem item = iter.next();
				if(item.isFormField())
				{
					String fieldname = item.getFieldName();
	                if(fieldname.equals("rid"))
	                {
	                	rid = item.getString();
	                	System.err.println("rid = " + rid);
	                }
	                else if(fieldname.equals("uid"))
	                {
	                	uid = item.getString();
	                	System.err.println("uid = " + uid);
	                }
	                else
	                {}
				}
			}
			String folderPath = servlet.getServletContext().getRealPath("/receiptImgs/") + uid;
			File file = new File(folderPath);
			if(!file.exists())
			{
				file.mkdir();
			}
			iter = fileItems.iterator();
			while(iter.hasNext())
			{
				FileItem item = (FileItem)iter.next();
				if(!item.isFormField())
				{
					String name = FilenameUtils.getName(item.getName());
					String ext = name.substring(name.lastIndexOf('.'));
                	System.err.println("name = " + name);
                	System.err.println("ext = " + ext);
					try
					{
						String filePath = folderPath + "/" + rid + ext;
						item.write(new File(filePath));
	                	System.err.println("finish writing file " + filePath);
						break;
					}
					catch(Exception e)
					{
						e.printStackTrace();
						System.err.println(e);
					}
				}
			}
		}
		catch(FileUploadException e)
		{
			e.printStackTrace();
			out.println(e);
		}
		catch (Exception e)
		{
			//out2.write("\nException " + e);
		}
		finally
		{
			out.close();
		}
	}
	
	private boolean folderExist(final String path)
	{
		File file = new File(path);
		return file.exists();
	}
}
