package fsenablers.android.http;


import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import android.util.Log;
import android.webkit.CookieManager;

import fsenablers.android.activity.WebAppActivity;

	
public class HttpUploadRequest {
	
        URL connectURL;
        String responseText;
        String Title;
        String Description;
        byte[ ] dataToServer;
        InputStream inputStream = null;
        String fileName;
        
        String mUploadField = "uploadedfile";
        Map<String,String> mAddFields;
      
        
        Boolean result;
        
        WebAppActivity mActivity;
        String mTxId;
        Boolean complete = Boolean.FALSE;

        public HttpUploadRequest( WebAppActivity aActivity, String sTxId, String urlString, String uploadField, Map<String,String> addFields, InputStream streamIn, String sFileName, String sTitle, String sDescription  ){
                
        		mActivity = aActivity;
        		mTxId = sTxId;
        		
        		try{
                        connectURL = new URL(urlString);
            
                }catch(Exception ex){
                    Log.i("HttpFileUpload","URL Malformatted");
                }
                
                inputStream = streamIn;
                fileName = sFileName;
                Title = sTitle;
                Description = sDescription;
                
                if( uploadField != null ) {
                	mUploadField = uploadField;
                }
                
                if( addFields != null ) {
                	mAddFields = addFields;
                } 
        }
        
        public String getFileName() {
        	return fileName;
        }
        public String getResponseText() {
        	return responseText;
        }
	
        WebAppActivity getMainActivity() {
        	return mActivity;
        }
        
        String getWebTransactionId() {
        	return mTxId;
        }
        
        Boolean getResult() {
        	return result;
        }
        
        Boolean getComplete() {
        	return complete;
        }

        void send(){
                // String iFileName = "ovicam_temp_vid.mp4";
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                String Tag="MyApp";
                try
                {
                	
                		CookieManager cm = CookieManager.getInstance();
                		
                		
                	
                        Log.i(Tag,"Starting Http File Sending to URL");
                        String cookieHeader = cm.getCookie( connectURL.toString() );
                		Log.i(Tag, "Cookie = " + cookieHeader );
                		
                		StringBuffer cfCookieParams = new StringBuffer();
                		
                		StringTokenizer t = new StringTokenizer( cookieHeader, " ;" );
                		
                		while( t.hasMoreElements() ) {
                			
                			String cookiePart = t.nextToken();
                			
                			List<HttpCookie> cookieList = HttpCookie.parse( cookiePart ); 
                			
                    		Iterator<HttpCookie> cookies = cookieList.iterator();
                    		while( cookies.hasNext() ) {
                    			
                    			HttpCookie cookie = cookies.next();
                    			
                    			Log.i(Tag, "Cookie: " + cookie.toString() );
                    			
                    			if( cookie.getName().equals( "CFID" ) || cookie.getName().equals( "CFTOKEN") ) {
                    				if( cfCookieParams.length() > 0 ) {
                    					cfCookieParams.append( "&" );
                    				}
                    				cfCookieParams.append( cookie.getName() + "=" + cookie.getValue() );
                    			}
                    		}
                			
                		}
                		
                		
                		
                		Log.i(Tag, "CookieParams = " + cfCookieParams.toString() );
                		URL newConnectURL = new URL ( connectURL.toString() + "?" + cfCookieParams.toString() );
                		
                		
	
                        // Open a HTTP connection to the URL
                        HttpURLConnection conn = (HttpURLConnection)newConnectURL.openConnection();
                        
                        Log.i( Tag, "URL is " + newConnectURL.toString() );
	
                        // 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=\"title\""+ lineEnd);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(Title);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                                      
                        dos.writeBytes("Content-Disposition: form-data; name=\"nameOfFile\""+ lineEnd);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(fileName);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + lineEnd);
	                        
                        dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(Description);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        
                        if( mAddFields != null ) {
                        	
                        	Iterator<String> keys = mAddFields.keySet().iterator();
                        	while( keys.hasNext() ) {

                        		String param = keys.next();
                        		String paramValue = mAddFields.get(param);
                        		
                        	
                        	 dos.writeBytes("Content-Disposition: form-data; name=\"" + param + "\""+ lineEnd);
                             dos.writeBytes(lineEnd);
                             dos.writeBytes(paramValue);
                             dos.writeBytes(lineEnd);
                             dos.writeBytes(twoHyphens + boundary + lineEnd);
                             
                             
                             Log.i(Tag, "Parameter:" + param + "=\"" + paramValue +"\"" );
                        	}
                        	
                        	
                        }
	                        
                        dos.writeBytes("Content-Disposition: form-data; name=\"" + mUploadField + "\";filename=\"" + fileName +"\"" + lineEnd);
                        dos.writeBytes(lineEnd);
	
                        Log.e(Tag,"Headers are written");
	
                        // create a buffer of maximum size
                        int bytesAvailable = inputStream.available();
                        Log.d("MyApp", "bytesAvailable = " + bytesAvailable );
	                        
                        int maxBufferSize = 1024;
                        int bufferSize = 1024; // Math.min(bytesAvailable, maxBufferSize);
                        byte[ ] buffer = new byte[bufferSize];
	
                        // read file and write it into form...
                        int bytesRead = inputStream.read(buffer, 0, bufferSize);
	
                        while (bytesRead > 0)
                        {
                        	 Log.d("MyApp", "bytesRead = " + bytesRead );
                                dos.write(buffer, 0, bytesRead );
                                // bytesAvailable = fileInputStream.available();
                                // bufferSize = Math.min(bytesAvailable,maxBufferSize);
                                bytesRead = inputStream.read(buffer, 0,bufferSize);
                        }
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	
                        // close streams
                        inputStream.close();
	                        
                        dos.flush();
	                        
                        Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

                        Log.e(Tag, "x-fse-uploadImage: " + conn.getHeaderField( "x-fse-uploadImage" ));
                        
                        
                        InputStream is = conn.getInputStream();
	                        
                        // retrieve the response from server
                        int ch;
	
                        StringBuffer b =new StringBuffer();
                        while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
                        responseText=b.toString();
                        Log.i(Tag, "Response: " + responseText);
                        dos.close();
                        result = Boolean.TRUE;
                }
                catch (MalformedURLException ex)
                {
                        Log.e(Tag, "URL error: " + ex.getMessage(), ex);
                        result = Boolean.FALSE;
                }
	
                catch (IOException ioe)
                {
                        Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
                        result = Boolean.FALSE;
                }
                
                complete = Boolean.TRUE;
                
        }
	

}