package cds;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletInputStream;
import java.util.Dictionary;
import java.util.Hashtable;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

// ---------------------------------------------------------
// class upload {
// ---------------------------------------------------------
public class upload {

  private String savePath, filepath, filename, contentType;
  private Dictionary fields;
  private boolean fileUpload=false;
  private boolean endUpload = false;

// ---------------------------------------------------------
// getEndUpload: name of the upload file
// ---------------------------------------------------------
  public boolean getEndUpload() {
    return endUpload;
  }
// ---------------------------------------------------------
// setEndUpload: name of the upload file
// ---------------------------------------------------------
  public void setEndUpload(boolean endupload) {
    this.endUpload = endupload;
  }

// ---------------------------------------------------------
// getFileUpload: name of the upload file
// ---------------------------------------------------------
  public boolean getFileUpload() {
    return fileUpload;
  }
// ---------------------------------------------------------
// setFileUpload: name of the upload file
// ---------------------------------------------------------
  public void setFileUpload(boolean fileupload) {
    this.fileUpload = fileupload;
  }

// ---------------------------------------------------------
// getFilename: name of the upload file
// ---------------------------------------------------------
  public String getFilename() {
    return filename;
  }
// ---------------------------------------------------------
// getFilepath: complete path of the upload file on the client
// ---------------------------------------------------------
  public String getFilepath() {
    return filepath;
  }
// ---------------------------------------------------------
// setSavePath: where the upload file should be save on the server
// ---------------------------------------------------------
  public void setSavePath(String savePath) {
    this.savePath = savePath;
  }
// ---------------------------------------------------------
// getContentType: specifies the type of the upload file content
// ---------------------------------------------------------
  public String getContentType() {
    return contentType;
  }
// ---------------------------------------------------------
// getFieldValue: stores  the name/value pairs of HTML form's input elements
// ---------------------------------------------------------
  public String getFieldValue(String fieldName) {
    if (fields == null || fieldName == null)
      return null;
    return (String) fields.get(fieldName);
  }
// ---------------------------------------------------------
// setFilename: name of the upload file
// ---------------------------------------------------------
  private void setFilename(String s) {
    if (s==null)
      return;

    int pos = s.indexOf("filename=\"");
    if (pos != -1) {
      filepath = s.substring(pos+10, s.length()-1);
      // Windows browsers include the full path on the client
      // But Linux/Unix and Mac browsers only send the filename
      // test if this is from a Windows browser
      pos = filepath.lastIndexOf("\\");
      if (pos != -1)
        filename = filepath.substring(pos + 1);
      else
        filename = filepath;
      // System.out.println("setfilename:" + filename);
    }
  }
// ---------------------------------------------------------
// setContentType
// ---------------------------------------------------------
  private void setContentType(String s) {
    if (s==null)
      return;

    int pos = s.indexOf(": ");
    if (pos != -1)
      contentType = s.substring(pos+2, s.length());
    System.out.println("contentType:" + contentType);
  }

// ---------------------------------------------------------
// do Upload
// ---------------------------------------------------------
  public void doUpload(HttpServletRequest request) throws IOException {

    ServletInputStream in = request.getInputStream();

    byte[] line = new byte[128];

    int i=0;

    try{
      // read the first line of HttpServletRequest objects's content
      i = in.readLine(line, 0, 128);

    // the first line should be the boundary and its length,
    // must be must longer than 3
    if (i < 3)
        return;

    //-2 discards the newline character
    int boundaryLength = i - 2;

    // the clean first line
    // example: -----------------------------7d15340138
    // Read from line start at 0 to boundaryLength
    String boundary = new String(line, 0, boundaryLength);
    //System.out.println("boundary:" + boundary);

    fields = new Hashtable();

    while (i != -1) {

      String newLine = new String(line, 0, i);
      //System.out.println("newLine:" + newLine);

      if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {

        // get the index where the substring "filename=\"" ends
        if (newLine.indexOf("filename=\"") != -1) {
          // save the name of the filename
          setFilename(new String(line, 0, i-2));
          // if this happens Houston we have a problem
          if (filename==null) {
            setFileUpload(false);
            return;
          }

          //From here we get the file
          i = in.readLine(line, 0, 128);
          // first we get the file content-type
          setContentType(new String(line, 0, i-2));
          i = in.readLine(line, 0, 128);
          // skip the blank line
          i = in.readLine(line, 0, 128);
          // get the next line
          newLine = new String(line, 0, i);

          // where to save the file
          PrintWriter pw= new PrintWriter(new BufferedWriter(
          new FileWriter((savePath==null? "" : savePath) + filename)));

          // while to get the file
          System.out.println("startfile");
          while (i != -1 && !newLine.startsWith(boundary)) {
            // the problem is the last line of the file content
            // contains the new line character.
            // So, we need to check if the current line is the last line.
            i = in.readLine(line, 0, 128);
            // + 4 is eof
            if ((i==boundaryLength+2 || i==boundaryLength+4) && (new String(line, 0, i).startsWith(boundary))) {
              pw.print(newLine.substring(0, newLine.length()-2));
              System.out.println("kkkk:" + newLine.substring(0, newLine.length()-2) + "@");
              }
            else {
              pw.print(newLine);
              System.out.println("yyyy:" + newLine + "@");
              }

            newLine = new String(line, 0, i);
            //System.out.println("newline:" + newLine);
          }
          System.out.println("endfile");
          pw.close();
          // flag of fileUpload with success
          setFileUpload(true);
        }
        else {
          // get the field name
          // get the index where the substring "name=\"" ends
          int pos = newLine.indexOf("name=\"");
          String fieldName = newLine.substring(pos+6, newLine.length()-3);

          // blank line
          i = in.readLine(line, 0, 128);
          i = in.readLine(line, 0, 128);
          newLine = new String(line, 0, i);
          StringBuffer fieldValue = new StringBuffer(128);
          while (i != -1 && !newLine.startsWith(boundary)) {
            // The last line of the field contains the new line character.
            // So, we need to check if the current line is the last line.
            i = in.readLine(line, 0, 128);
            // + 4 is eof
            if ((i==boundaryLength+2 || i==boundaryLength+4) && (new String(line, 0, i).startsWith(boundary)))
              fieldValue.append(newLine.substring(0, newLine.length()-2));
            else
              fieldValue.append(newLine);
            newLine = new String(line, 0, i);
          }
          System.out.println("fieldValue:" + fieldValue.toString());
          fields.put(fieldName, fieldValue.toString());
        }
      }
      i = in.readLine(line, 0, 128);

    } // end while
    // flag of fileUpload method ends
    setEndUpload(true);
    }
    catch(java.io.IOException ioe){
      ioe.printStackTrace();
    }
  }

// ---------------------------------------------------------
// END
// ---------------------------------------------------------

}