// This code grabbed (then modified) from:
//
// http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
//
// The idea of using this class is to run a simple PHP file uploader on the
// server and upload images via http (which lets me use existing technology
// rather than building a custom server to run on the host).

package lan.my.zooty.andyscan;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

public class PictureUploader implements Runnable {

   URL connectURL;
   String responseString;
   String fileName;
   byte[] jpegData;
   String Tag="Preview";

   // I get a byte[] buffer from the camera callback when I take a picture,
   // so just pass that buffer to the uploader along with the name I want to
   // give the file when it is uploaded along with the URL for the web
   // server where I'll upload it.

   PictureUploader(String urlString, String fileName, byte[] data) {
      Log.i(Tag,"In PictureUploader constructor");
      try {
         connectURL = new URL(urlString);
      } catch(Exception ex){
         Log.i(Tag,"MALFORMATED URL");
      }
      this.fileName = fileName;
      jpegData = data;
   }

   // Open the web server and upload the file in the separate thread.

   public void run() {
      Log.i(Tag, "In PictureUploader run()");
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****14cac5ad-6280-4a5c-b012-bdfcc73883ac*****";
      try {

         //------------------ CLIENT REQUEST

         Log.e(Tag,"Starting to bad things");

         // Open a HTTP connection to the URL

         HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

         // Allow Inputs
         conn.setDoInput(true);

         // Allow Outputs
         conn.setDoOutput(true);

         // Don't use a cached copy.
         conn.setUseCaches(false);

         // Use a post method.
         conn.setRequestMethod("POST");

         conn.setRequestProperty("Connection", "Keep-Alive");

         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

         DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );

         dos.writeBytes(twoHyphens + boundary + lineEnd);
         dos.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" + fileName +"\"" + lineEnd);
         dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
         dos.writeBytes(lineEnd);

         Log.e(Tag,"Headers are written");

         // I've got the buffer with the whole jpeg file in it already,
         // might as well just write the whole thing and see if it works (I
         // suppose can loop writing smaller chunks at a time if this has
         // problems).

         dos.write(jpegData, 0, jpegData.length);

         // send multipart form data necesssary after file data...

         dos.writeBytes(lineEnd);
         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

         // close streams

         Log.e(Tag,"File is written");
         dos.flush();

         InputStream is = conn.getInputStream();

         // retrieve the response from server

         int ch;

         StringBuffer b =new StringBuffer();
         while( ( ch = is.read() ) != -1 ){
            b.append( (char)ch );
         }
         String s=b.toString(); 
         Log.i("Response",s);
         dos.close();
      } catch (MalformedURLException ex) {
         Log.e(Tag, "error: " + ex.getMessage(), ex);
      } catch (IOException ioe) {
         Log.e(Tag, "error: " + ioe.getMessage(), ioe);
      }
      // PUT CODE HERE - I should do a RunOnUiThread call to tell UI the
      // picture is uploaded and it can restart the preview.
   }
}
