package com.example.TreballFiGrau;

import java.io.ByteArrayOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
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.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
 
/**
 * This activity displays the gallery image picker.
 * It displays the image that was picked.
 *
 * @author ITCuties
 *
 */
public class PujarFoto extends Activity implements OnClickListener {
 
    // Image loading result to pass to startActivityForResult method.
    private static int LOAD_IMAGE_RESULTS = 1;
     
    // GUI components
    private Button button;  // The button
    private ImageView image;// ImageView
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.foto);
      //ImageView imageView = (ImageView) findViewById(R.id.imgView);
        //imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 
        // Find references to the GUI objects
        //button = (Button)findViewById(R.id.button);
        //image = (ImageView)findViewById(R.id.image);
         
        // Set button's onClick listener object.
        button.setOnClickListener(this);
         
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("aki","pujar foto 1");
        // Here we need to check if the activity that was triggers was the Image Gallery.
        // If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
        // If the resultCode is RESULT_OK and there is some data we know that an image was picked.
        if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
            // Let's read picked image data - its URI
            Uri pickedImage = data.getData();
            // Let's read picked image path using content resolver
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
             
            // Now we need to set the GUI ImageView data with data read from the picked file.
            // ----------AIXO FUNCIONA----- (linia d sota)
            //image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            
            //image.setImageBitmap(imatge.imatge);
             
            // At the end remember to close the cursor or you will end with the RuntimeException!
            cursor.close();
            String imgStringBase64 = bitMap(imagePath);
            //AfegirFotoWeb task = new AfegirFotoWeb();
            //task.execute(new String[] { imgStringBase64 });
            Imatge imatge = new Imatge();
            Runnable r = new AfegirFotoWeb(imgStringBase64,imatge);
        	new Thread(r).start();
        	while(imatge.b==false){
        		//Log.d("aki","dintre while");
        	}
        	Log.d("aki","despres thread");
        	
        	image.setImageBitmap(imatge.imatge);
        }
    }
     
    @Override
    public void onClick(View v) {
        // Create the Intent for Image Gallery.
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
         
        // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
        startActivityForResult(i, LOAD_IMAGE_RESULTS);
    }


        	//String cosa = bitMap(picturePath); //aixo es el k enviarem per json a la web
        	//String cosa = getStringFromBitmap(bmp);

		
            
            
            

           
            //Runnable r = new AfegirFotoWeb();
        	//new Thread(r).start();
           
            
		
            

         
       
     
     
    
    
    
    //funcio que transforma una direccio d'imatge a string per pasar despres en format json a la web
    public String bitMap(String adresa){
    	Log.d("aki","bitmap 1");
    	Bitmap bm = BitmapFactory.decodeFile(adresa);
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    	bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
    	byte[] b = baos.toByteArray(); 
    	String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
    	Log.d("aki","bitmap 2");
    	return encodedImage;
    }
    
    //funcio que reb un json desde la web i la transforma a una imatge k es pot mostrar per la view
    public void pillarFoto(JSONObject jsonRebut) throws JSONException{
    	Log.d("aki","dintre pillar foto");
   
        
        String value2 = jsonRebut.getString("imatge");
    
        Log.d("aki", value2);
        
        
        byte[] decodedString = Base64.decode(value2, Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

        
        
        //ImageView imageView = (ImageView) findViewById(R.id.imgView);
        //imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        
        //Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.decodedByte);
        //ImageView view = (ImageView)findViewById(R.id.imgView);
        //view.setImageBitmap(decodedByte);
    }






}