package com.appli.gui;


import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;



import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;

import com.appli.patoche.R;

// Bitmap resized = ThumbnailUtils.extractThumbnail(sourceBitmap, width, height);
//http://www.thaicreate.com/mobile/android-listview-imageview-sdcard.html

public class miniature_thumbnail extends Activity {
	  
    List <String> ImageList;
    private File root;
    private ArrayList<File> fileList = new ArrayList<File>();
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_miniature_layout);
        
        /*** Get Images from SDCard ***/
        
        //root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());

        clean();
        create_miniatures();
        ImageList = find_miniatures();
        //ImageList = getSD();
       // ImageList = test();
        
        
        // listView1
        final ListView LView1 = (ListView)findViewById(R.id.listView1); 
        	
        LView1.setAdapter(new ImageAdapter(this,ImageList));
               
        final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        
        LView1.setOnItemClickListener(new OnItemClickListener() 
        {
			public void onItemClick(AdapterView<?> parent, View v,	int position, long id) 
			{
				String strPath = ImageList.get(position).toString();
                String name = new File(strPath).getName();
                Toast.makeText(miniature_thumbnail.this, name , Toast.LENGTH_LONG).show();
                Intent intent = new Intent(miniature_thumbnail.this , miniature_full.class);
                intent.putExtra("selected-item", name);
                startActivity(intent);  

                
			}
		});
    
      
    }

    
    public ArrayList<File> getfile(File dir) 
    {
		File listFile[] = dir.listFiles();
		if (listFile != null && listFile.length > 0) {
			for (int i = 0; i < listFile.length; i++) {

				if (listFile[i].isDirectory()) {
					fileList.add(listFile[i]);
					getfile(listFile[i]);

				} else {
					if (listFile[i].getName().endsWith(".png")
							|| listFile[i].getName().endsWith(".jpg")
							|| listFile[i].getName().endsWith(".jpeg")
							|| listFile[i].getName().endsWith(".gif"))

					{
						fileList.add(listFile[i]);
					}
				}

			}
		}
		return fileList;
	}


    
    //http://tutorial4android.com/android_file_folder.php
    
    private void clean()
    {
    	File f = new File ("/mnt/sdcard");
	    File[] files = f.listFiles();
		
	    for (int i = 0; i <files.length; i++)
	    {
	    	File  file = files[i];
	    	int lastIndex = 0;
	    	
	    	String filename = file.getPath();
	    	lastIndex = filename.indexOf("mini",lastIndex);

	        if( lastIndex != -1)
	        {
	        	//File file = new File(selectedFilePath);
	        	boolean deleted = file.delete();
	        	Log.d("---- Deleted -----",file.getPath());
	        }
	    }	
    	
    }
    
    private void create_miniatures()
    {
    	
    	List <String> it = new ArrayList <String>();
 	    File f = new File ("/mnt/sdcard");
 	    File[] files = f.listFiles ();
 		
 	    for (int i = 0; i <files.length; i++)
 	    {
 	    	File  file = files[i];
 		    
 	    	String extension = file.getPath().substring(file.getPath().lastIndexOf('.') + 1);
 	        if(extension.equals("jpg"))
 	        {
 		    	Log.d("---------",file.getPath());
 	        	it.add (file.getPath());
 	    
 	        	String filename = file.getPath().substring(file.getPath().lastIndexOf("/")+1);
 	        	String new_name = "/mnt/sdcard/" + "mini_" + filename;
 	
 	        	Bitmap bitmap = BitmapFactory.decodeFile( file.getPath());
 	        	Bitmap resized = ThumbnailUtils.extractThumbnail(bitmap, 100, 100);
 	    
 	        	File sdCardDirectory = Environment.getExternalStorageDirectory();
 	        	File image_file = new File( new_name);

 	    
 	        	try 
 	        	{
 	        		FileOutputStream out = new FileOutputStream(image_file);
 	        		resized.compress(Bitmap.CompressFormat.JPEG, 100, out);
 	        		out.flush();
 	        		out.close();
 	        	} 
 	        	catch (Exception e) 
 	        	{
                 
 	        	}
 	        	
 			    it.add (new_name);
     	
 	        }	 
 		    
 	   }
 	    
    }
    	
    private List <String> find_miniatures()
    {
    	List <String> images = new ArrayList <String>();
    	File f = new File ("/mnt/sdcard");
	    File[] files = f.listFiles();
		
	    for (int i = 0; i <files.length; i++)
	    {
	    	File  file = files[i];
	    	int lastIndex = 0;
	    	
	    	String filename = file.getPath();
	    	lastIndex = filename.indexOf("mini",lastIndex);

	        if( lastIndex != -1)
	        {
	        	images.add (file.getPath());
	        	Log.d("---- Find miniatures -----",file.getPath());
	        }
	    }
	    
	    return images;
    }
    
    private List <String> getSD()
    {
	    List <String> it = new ArrayList <String>();
	    File f = new File ("/mnt/sdcard");
	    File[] files = f.listFiles ();
		
	    for (int i = 0; i <files.length; i++)
	    {
	    	File  file = files[i];
		    
	    	String extension = file.getPath().substring(file.getPath().lastIndexOf('.') + 1);
	        if(extension.equals("jpg"))
	        {
		    	Log.d("---------",file.getPath());
	        	it.add (file.getPath());
	    
	        	String filename = file.getPath().substring(file.getPath().lastIndexOf("/")+1);
	        	String new_name = "/mnt/sdcard/" + "mini_" + filename;
	
	        	Bitmap bitmap = BitmapFactory.decodeFile( file.getPath());
	        	Bitmap resized = ThumbnailUtils.extractThumbnail(bitmap, 100, 100);
	    
	        	File sdCardDirectory = Environment.getExternalStorageDirectory();
	        	File image_file = new File( new_name);

	    
	        	try 
	        	{
	        		FileOutputStream out = new FileOutputStream(image_file);
	        		resized.compress(Bitmap.CompressFormat.JPEG, 100, out);
	        		out.flush();
	        		out.close();
	        	} 
	        	catch (Exception e) 
	        	{
                
	        	}
	        	
			    it.add (new_name);
    	
	        }	 
		    
	   }
	    
	    return it;
	    
	    
    }
    
    private List <String> test()
    {
    	    List <String> images = new ArrayList <String>();
    	/*
    	 	String parentDirectory = "/mnt/sdcard";
	        File dirFileObj = new File(parentDirectory);
	        File[] files = dirFileObj.listFiles();
	        
	        for (File file : files)
	        {
	            if (file.isFile() )
	            {
	            	  if(file.getName().toUpperCase().endsWith(("JPG")) )
	            	  {
	            		  String fullpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + file.getName();
	            		  images.add (fullpath);
	            		  Log.d("---------", fullpath);
	            	  }
	            } 
	            
	        }
	    */    
	        
	    		images.add ("/mnt/sdcard/aaa.jpg");
	    		images.add ("/sdcard/bbb.jpg");
	    		images.add ("/sdcard/ccc.jpg");
	    		images.add ("/mnt/sdcard/recu.jpg");
	    		
	    		images.add ("/sdcard/test.jpg");
	    		images.add ("/sdcard/tmp.jpg");
	    		images.add ("/mnt/sdcard/nadatest.jpg");
/*
	    		images.add ("/mnt/sdcard/aaa.jpg");
	    		images.add ("/sdcard/bbb.jpg");
	    		images.add ("/sdcard/ccc.jpg");
	    		images.add ("/mnt/sdcard/recu.jpg");

	    		
	    		images.add ("/mnt/sdcard/aaa.jpg");
	    		images.add ("/sdcard/bbb.jpg");
	    		images.add ("/sdcard/ccc.jpg");
	    		images.add ("/mnt/sdcard/recu.jpg");
*/
    	
	        return images;
    }
    
    public class ImageAdapter extends BaseAdapter 
    {
        private Context context;
        private List <String> lis;
        
        public ImageAdapter(Context c, List <String> li) 
        {
        	// TODO Auto-generated method stub
            context = c;
            lis = li;
        }
 
        public int getCount() {
        	// TODO Auto-generated method stub
            return lis.size();
        }
 
        public Object getItem(int position) {
        	// TODO Auto-generated method stub
            return position;
        }
 
        public long getItemId(int position) {
        	// TODO Auto-generated method stub
            return position;
        }
        
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		 
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.image_miniature_colonne_layout, null);
			}
					
			// ColImage
			String strPath = lis.get(position).toString();
			Bitmap bm = BitmapFactory.decodeFile(strPath);

			ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImage);
			imageView.getLayoutParams().height = 100;
			imageView.getLayoutParams().width = 100;
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setImageBitmap(bm);
			
			// ColPosition
			//TextView txtPosition = (TextView) convertView.findViewById(R.id.ColPosition);
			//txtPosition.setPadding(10, 0, 0, 0);
			//int index = position + 1;
			//String val = Integer.toString(index) 
			//txtPosition.setText(Integer.toString(index));
			
			// ColPicname
			TextView txtPicName = (TextView) convertView.findViewById(R.id.ColPicname);
			txtPicName.setPadding(50, 0, 0, 0);
			String fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length());
			fileName = fileName.replace("mini_","");
			txtPicName.setText(fileName);

			// ColTaille
			TextView txtTaille = (TextView) convertView.findViewById(R.id.ColTaille);
			txtTaille.setPadding(50, 0, 0, 0);
			File file =new File("/sdcard/" + fileName);
			String filesize = getFileSize(file);
			
			Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/" + fileName);
   		    int width = bitmap.getWidth();
   		    int height = bitmap.getHeight();

   		    String concat = filesize + "  " + Integer.toString(width) + "px " + Integer.toString(height) + "px ";
   		    txtTaille.setText(concat);
		 
			return convertView;
			
			
				
		}

    } 
    
    public String getFileSize(File file)
    {
        String modifiedFileSize = null;
        double fileSize = 0.0;
        
        if(file.isFile())
        {
            fileSize = (double) file.length();  //in Bytes

            if (fileSize < 1024) 
            {
                modifiedFileSize = String.valueOf(fileSize).concat("B");
            } 
            else if (fileSize > 1024 && fileSize < (1024 * 1024)) 
            {
                modifiedFileSize = String.valueOf(Math.round((fileSize / 1024 * 100.0)) / 100.0).concat("KB");
            } 
            else 
            {
                modifiedFileSize = String.valueOf(Math.round((fileSize / (1024 * 1204) * 100.0)) / 100.0).concat("MB");
            }
        }
        
        else 
        {
            modifiedFileSize = "Unknown";
        }

        return modifiedFileSize;
    }
    
    
   

}
