package com.esurfer.common;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.text.SimpleDateFormat;
import java.io.*;
import org.apache.commons.fileupload.*;
public class UploadFile {
   private String tmpdir;
   private String updir;
   private HttpServletRequest request;
   
   public HttpServletRequest getRequest() {
       return request;
   }
   public void setRequest(HttpServletRequest request) {
       this.request = request;
   }
 
 
   public String getTmpdir() {
       return tmpdir;
   }
   public void setTmpdir(String string) {
       tmpdir = string;
   } 
 
 
   public String getUpdir() {
       return updir;
   }
   public void setUpdir(String string) {
       updir = string;
   }
 
   /**
    * Create directory with the name 'path'
    * @param path
    * @return
    */ 
   private String MkDir(String path) {
       String msg = null;
       java.io.File dir;
       // Create new file object
       dir = new java.io.File(path);
       if (dir == null) {
           msg = "Error:<BR>Can't create empty directory!";
           return msg;
       }
       if (dir.isFile()) {
           msg = "Error:<BR>File name <B>" + dir.getAbsolutePath() + 
                 "</B> already exists!";
           return msg;
       }
       if (!dir.exists()) {
           boolean result = dir.mkdirs();
           if (result == false) {
               msg = "Error:<BR>Create directory <b>" + 
                     dir.getAbsolutePath() + "</B> failed!";
               return msg;
           }
           return msg;
       } else {
       }
       return msg;
   }
 
   /**
    * Get current datetime used to name a file uploaded
    * @return
    */
   private String getCurDateTime(){
       SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
       return df.format(new Date());
   }
 
   /**
    * Upload files
    * @return
    */
   public String[] uploadFile() {
       String msg = "";
       String img = null;
  
       // the final filename of the file uploaded
       String sFinalName = "";
  
       DiskFileUpload fu = new DiskFileUpload();
 
       // maximum size in byte that permitted to upload
       fu.setSizeMax(51200);
 
       // maximum size in byte that will be stored in memory
       fu.setSizeThreshold(4096);
 
       // the tempory path that the file(s) will be stored 
       // when greater than getSizeThreshold()
       fu.setRepositoryPath(tmpdir);
 
       // begin read information of upload
       List fileItems = null;
       try {
           fileItems = fu.parseRequest(request);
       } catch (FileUploadException e) {
           System.err.println("Upload File Failed!");
       }
       // process each file uploaded
       Iterator iter = fileItems.iterator();
 
       // root dir to store file uploaded
       String uproot = updir;
  
       // ArrayList used to save uploaded file name
       ArrayList uploadedFiles = new ArrayList();
  
       String filepath = updir;
       String opmsg = MkDir(filepath);
       if (opmsg == null) {
           while (iter.hasNext()) {
               FileItem item = (FileItem) iter.next();
         
               // Ignore the other type of form field(s) except file
               if (!item.isFormField()) {
                   String name = item.getName();
                   long size = item.getSize();
                   if ((name == null || name.equals("")) && size == 0) {
                       continue;
                   }
                   name = name.replace('\\','/');
                   File fullFile = new File(name); 
                   // get the extension
                   String sExtension = fullFile.getName().substring(
                          fullFile.getName().lastIndexOf("."), 
                          fullFile.getName().length());            
                   // Generate the new filename
                   String sNewFileName = getCurDateTime() + sExtension;
          
                   // Set the final filename to sNewFileName
                   sFinalName = sNewFileName;
     
                   // Create the file with the generated name 
                   File savedFile = new File(filepath, sNewFileName);
          
                   // If the file already exist, assign a new name to it
                   for (int k = 0; savedFile.exists(); k++) {
                       // get the file name from the variable
                       String sTmpFileName = sNewFileName;    
         
                       // get the file name except the extension
                       String sFileName = sNewFileName.substring(0, 
                                          sNewFileName.lastIndexOf("."));    
         
                       // combine a new file name
                       savedFile = new File(filepath, sFileName + k + sExtension);    
         
                       // get the new generated file name as the final filename
                       sFinalName = sFileName + k + sExtension;   
                   }
                   try {
                       item.write(savedFile);
                   } catch (Exception e1) {
                       System.err.println("Upload File Failed!");
                   }
                   uploadedFiles.add(sFinalName);
               }
           }
       }
       String sUploadedFileNames[] = new String[uploadedFiles.size()];
       uploadedFiles.toArray(sUploadedFileNames);
       return sUploadedFileNames;
     }  
 }