package com.example.listviewcustom03;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class NewContact extends Activity 
{	
	ImageView iv_user_photo; 
	
	private static int RESULT_LOAD_IMAGE = 1;
	
	private ContactHandler handler;
	
	private String picturePath = "";
	
	private String nom;
	private String prenom;
	private String adresse;
	private String email;
	private String portable;
	private String fixe;
	private String photograph;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_contact);
		
		handler = new ContactHandler(getApplicationContext());
		
		iv_user_photo = (ImageView) findViewById(R.id.iv_user_photo);
		
		iv_user_photo.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(intent, RESULT_LOAD_IMAGE);	
				//selectImage();
			}
		});
				
		Button btn_add = (Button) findViewById(R.id.btn_add);
		btn_add.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View arg0) 
			{
				
				EditText et_name = (EditText) findViewById(R.id.et_nom);
				nom = et_name.getText().toString();
				
				EditText et_prenom = (EditText) findViewById(R.id.et_prenom);
				prenom = et_prenom.getText().toString();
				
				EditText et_adresse = (EditText) findViewById(R.id.et_adresse);
				adresse = et_adresse.getText().toString();
				
				EditText et_email = (EditText) findViewById(R.id.et_email);
				email = et_email.getText().toString();
				
				EditText et_portable = (EditText) findViewById(R.id.et_portable);
				portable = et_portable.getText().toString();
				
				EditText et_fixe = (EditText) findViewById(R.id.et_fixe);
				fixe = et_fixe.getText().toString();
				
				ImageView iv_photograph = (ImageView) findViewById(R.id.iv_user_photo);
				photograph = picturePath;
				
				Contact contact = new Contact();
				
				contact.setNom(nom);
				contact.setPrenom(prenom);
				contact.setAdresse(adresse);
				contact.setEmail(email);
				contact.setPortable(portable);
				contact.setFixe(fixe);
				contact.setPhotograph(photograph);
				
				if(nom.isEmpty())
				{	
					Toast.makeText(getApplicationContext(), "Champs vide ?", Toast.LENGTH_LONG).show();
				}
				else
				{	
					Toast.makeText(getApplicationContext(), "On sauve ...", Toast.LENGTH_LONG).show();
					/*
					Boolean added = handler.addContactDetails(contact);
					if(added)
					{
						Intent intent = new Intent(NewContact.this, MainActivity.class);
						startActivity(intent);
					}
					else
					{
						Toast.makeText(getApplicationContext(), "Contact data not added. Please try again", Toast.LENGTH_LONG).show();
					}*/
				}		
				
			}
		});
		
	}
	
	
	 private void selectImage()
	 {

	        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

	        AlertDialog.Builder builder = new AlertDialog.Builder(NewContact.this);
	        builder.setTitle("Add Photo!");
	        builder.setItems(options, new DialogInterface.OnClickListener() {

	            @Override
	            public void onClick(DialogInterface dialog, int item) {

	                if (options[item].equals("Take Photo"))
	                {
	                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
	                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
	                    startActivityForResult(intent, 1);
	                }

	                else if (options[item].equals("Choose from Gallery"))
	                {
	                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	                    startActivityForResult(intent, 2);
	                }

	                else if (options[item].equals("Cancel")) 
	                {
	                    dialog.dismiss();
	                }

	            }

	        });

	        builder.show();

	    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
			super.onActivityResult(requestCode, resultCode, data);
			
			if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
			{
	            Uri imageUri = data.getData();
	            String[] filePathColumn = { MediaStore.Images.Media.DATA };
	            Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
	            cursor.moveToFirst();
	 
	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            picturePath = cursor.getString(columnIndex);
	            cursor.close();
	             
	            ImageView imageView = (ImageView) findViewById(R.id.iv_user_photo);
	            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
	         
	        }
	}

	
	/*********** Nouvelle implementation pas encore clean ****************/
	
	 protected void _______XXXXXonActivityResult(int requestCode, int resultCode, Intent data) 
	 {

	        super.onActivityResult(requestCode, resultCode, data);

	        if (resultCode == RESULT_OK)
	        {
	            	if (requestCode == 1)
	            	{
	                		File f = new File(Environment.getExternalStorageDirectory().toString());
			                
	                		for (File temp : f.listFiles()) 
			                {
			                    if (temp.getName().equals("temp.jpg"))
			                    {
			                        f = temp;
			                        break;
			                    }
			                }

	                		try 
	                		{
				                    Bitmap bitmap;
				                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
				                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions); 
				                    iv_user_photo.setImageBitmap(bitmap);
			
				                    String path = android.os.Environment
				                            .getExternalStorageDirectory()
				                            + File.separator
				                            + "Phoenix" + File.separator + "default";
			
				                    f.delete();
				                    OutputStream outFile = null;
				                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

				                    try 
				                    {
				                        outFile = new FileOutputStream(file);
				                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
				                        outFile.flush();
				                        outFile.close();
				                    } 
				                    
				                    catch (FileNotFoundException e)
				                    {
				                    	e.printStackTrace();
				                    }
				                    
				                    catch (IOException e) 
				                    {
				                    	e.printStackTrace();
				                    }
				                    
				                    catch (Exception e)
				                    {
				                    	e.printStackTrace();
				                    }

	                		} 
	                		
	                		catch (Exception e)
	                		{
	                			e.printStackTrace();
	                		}

	            	} 
	            
	            	else if (requestCode == 2) 
	            	{

	            			Uri selectedImage = data.getData();
	            			String[] filePath = { MediaStore.Images.Media.DATA };
	            			Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
	            			c.moveToFirst();
	            			int columnIndex = c.getColumnIndex(filePath[0]);
	            			String picturePath = c.getString(columnIndex);
	            			c.close();
	            			Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
	            			Log.w("path of image from gallery......******************.........", picturePath+"");
	            			iv_user_photo.setImageBitmap(thumbnail);
	            	}

	        }

	 }

	
	
	
	/****************************/
	
}
