package app.hima.tool;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.widget.Toast;

public class ImageUploadService extends IntentService {
	private final static String NAME = "ImageUpload";

	public ImageUploadService() {
		super(NAME);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Uri data = intent.getData();
		
		Log.d(this.getClass().getSimpleName(), data.toString());
		
		int no = intent.getIntExtra("no", 1);
		doHttpUpload(data, no);
	}
		
	public void doHttpUpload(Uri myImage, int no) {
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String photofile = null;
		String httpResponse; // to read http response
		String filename = null;

		String urlString = "http://app.kimiko.be/deai/addImage.pl";
		HttpURLConnection conn = null;

		InputStream fis = null;
		Bitmap mBitmap = null;
		String pathfile;

		if (myImage != null) {
			// on récupère le nom du fichier photo construit avec date et heure
			filename = Preferences.id + "-" + no + ".jpg";

			String[] projection = {MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
			ContentResolver cr = getContentResolver();
			Cursor c = cr.query(myImage, projection, null, null, null);
			if (c != null && c.moveToFirst()) {
				pathfile = c.getString(0); // column0Value
				photofile = c.getString(1); // column1Value
				Log.i(getClass().getSimpleName(), "Data : " + pathfile);
				Log.i(getClass().getSimpleName(), "Display name : " + photofile);
			}

			try {
				fis = getContentResolver().openInputStream(myImage);
				mBitmap = BitmapFactory.decodeStream(fis);

				try {
					//int bytesAvailable = fis.available();
					fis.available();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.i(getClass().getSimpleName(), "échec de lecture de la photo");
					stopSelf();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				Toast.makeText(this,
						"échec de lecture de la photo ", Toast.LENGTH_SHORT)
						.show();
				Log.i(getClass().getSimpleName(),
						"échec de lecture de la photo");
				stopSelf();
			}

		} else
			Log.i(getClass().getSimpleName(), "myImage is null");

		try {
			URL site = new URL(urlString);
			conn = (HttpURLConnection) site.openConnection();

			// on peut écrire et lire
			conn.setDoOutput(true);
			conn.setDoInput(true);

			// Use a post method.
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
			//conn.setRequestProperty("Content-Length", );

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

			dos.writeBytes(twoHyphens + boundary + lineEnd);
			Log.i(getClass().getSimpleName(), "Display name : " + photofile);
			Log.i(getClass().getSimpleName(), "Filename : " + filename);
			

			dos.writeBytes("content-disposition: form-data; name=\"no\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes("1");
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			
			dos.writeBytes("content-disposition: form-data; name=\"user\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(String.valueOf(Preferences.id));
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			
			
			dos.writeBytes("content-disposition: form-data; name=\"fichierNom\""+ lineEnd);
			dos.writeBytes(lineEnd);
			dos.writeBytes(filename);
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + lineEnd);
			
			//Content-Disposition: form-data; name="fichier"; filename="1013674_10201207111116823_1510595656_n.jpg"
			//Content-Type: image/jpeg
			
			dos.writeBytes("Content-Disposition: form-data; name=\"fichier\";filename=\""+ filename + "\"" + lineEnd);
			//dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
			dos.writeBytes(lineEnd);

			Log.i(getClass().getSimpleName(), "Headers are written");

			// compression de image pour envoi
			mBitmap.compress(CompressFormat.JPEG, 75, dos);

			// send multipart form data necesssary after file data...
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + lineEnd);

			// close streams
			fis.close();
			dos.flush();
			dos.close();
			Log.e("fileUpload", "File is written on the queue");

		} catch (MalformedURLException e) {
			e.printStackTrace();
			Toast.makeText(this,"échec de connexion au site web ", Toast.LENGTH_SHORT).show();
			Log.i(getClass().getSimpleName(),"échec de connexion au site web 1");
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(this,"échec de connexion au site web ", Toast.LENGTH_SHORT).show();
			Log.i(getClass().getSimpleName(),"échec de connexion au site web 2");
		}

		//lecture de la réponse http
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			Log.i(getClass().getSimpleName(), "try HTTP reponse");
			while ((httpResponse = rd.readLine()) != null) {
				Log.i(getClass().getSimpleName(), "HTTP reponse= "+ httpResponse);
				if (httpResponse.contains("error")) {
					Log.i(getClass().getSimpleName(), "HTTP reponse= error");
				}
			}
			rd.close();
		} catch (IOException ioex) {
			Log.e("HttpUploader", "error: " + ioex.getMessage(), ioex);
			ioex.printStackTrace();
			Toast.makeText(this,
					"échec de lecture de la réponse du site web ",
					Toast.LENGTH_SHORT).show();
			Log.i(getClass().getSimpleName(),
					"échec de lecture de la réponse du site web");
		}

	}
}
