package com.example.send01;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
 
import android.util.Log;

public class MainActivity extends Activity {

    private Socket client;
    private FileInputStream fileInputStream;
    private BufferedInputStream bufferedInputStream;
    private OutputStream outputStream;
    private Button button1, button2 ;
    private TextView textview;
    private ImageView image;

    String filename;
    String filecontent;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        image = (ImageView)findViewById(R.id.jpgview);
        
        textview = (TextView)findViewById(R.id.textView1);
        
        button1 = (Button) findViewById(R.id.button1);  
        
        button1.setOnClickListener(new View.OnClickListener() 
        {

            public void onClick(View v)
            {
            	load_image();
            	
            	Toast.makeText(getApplicationContext(), "Download ...", Toast.LENGTH_SHORT).show();
            		/*
	                File file = new File("/mnt/sdcard/image.jpg"); 
	
		                try 
		                {
		
		                    client = new Socket("10.0.2.2", 4444);
		
		                    byte[] mybytearray = new byte[(int) file.length()]; 
		
		                    fileInputStream = new FileInputStream(file);
		                    bufferedInputStream = new BufferedInputStream(fileInputStream);
		
		                    bufferedInputStream.read(mybytearray, 0, mybytearray.length); 
		
		                    outputStream = client.getOutputStream();
		
		                    outputStream.write(mybytearray, 0, mybytearray.length); 
		                    outputStream.flush();
		                    bufferedInputStream.close();
		                    outputStream.close();
		                    client.close();
		                } 
	                
			            catch (UnknownHostException e) 
			            {
			                 e.printStackTrace();
			            } 
			
			            catch (IOException e)
			            {
			                 e.printStackTrace();
			            }
		                
		                
		                */
	         }
        });
        
        
        button2 = (Button) findViewById(R.id.button2);   

        button2.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v) 
            {

            	filename = "petit essai";
            	filecontent = "zorro";
            	
            	FileOperations fop = new FileOperations();
                fop.write(filename, filecontent);

                if(fop.write(filename, filecontent))
                {
                	Toast.makeText(getApplicationContext(), filename+".txt created", Toast.LENGTH_SHORT).show();
                }
                
                else
                {
                    Toast.makeText(getApplicationContext(), "I/O error", Toast.LENGTH_SHORT).show();
                }
                
                
                
                String text = fop.read(filename);
                if(text != null)
                {
                	textview.setText(text);
                }
                               
            }
        });
        
        
        
      /*  
        File imageFile2 =new File(Environment.getExternalStorageDirectory(),"/images/"+imagef2);
		
        if(imageFile2!=null)
  	      {
  	Bitmap bitmap2 = BitmapFactory.decodeFile(imageFile2.getAbsolutePath());
       imageview.setImageBitmap(bitmap2);
  		      }
        
     */
        
    
        
       
   //     image = (ImageView)findViewById(R.id.jpgview);
  //      String myJpgPath = "/sdcard/aaaadownloadedfile.jpg";
      
  //      Bitmap bm = BitmapFactory.decodeFile(myJpgPath);
 //       image.setImageBitmap(bm);
        

    }
    
    
    void load_image()
    {
        			URL imageURL = null;
        
		            try
		            {
		            	
		                imageURL = new URL("http://www.analog-design.net/ALARME/Videos/beach.jpg");         
		                HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
		                connection.setDoInput(true);
		                connection.connect();
		                InputStream inputStream = connection.getInputStream();
		                Bitmap bm = BitmapFactory.decodeStream(inputStream);
		                image.setImageBitmap(bm);
		            } 
		            
		            catch (IOException e)
		            {
		                e.printStackTrace();
		            }
    }

}



class FileOperations
{
    public FileOperations()
    {

    }

    public Boolean write(String fname, String fcontent)
    {
           try 
           {

               String fpath = "/sdcard/"+fname+".txt";

               File file = new File(fpath);

               // If file does not exists, then create it
               if (!file.exists()) 
               {
                   file.createNewFile();
               }

               FileWriter fw = new FileWriter(file.getAbsoluteFile());
               BufferedWriter bw = new BufferedWriter(fw);
               bw.write(fcontent);
               bw.close();

               Log.d("Suceess","Sucess");
               return true;

           } 
           
           catch (IOException e) 
           {
               e.printStackTrace();
               return false;
           }

    }

    public String read(String fname)
    {

        BufferedReader br = null;
        String response = null;

           try {

               StringBuffer output = new StringBuffer();
               String fpath = "/sdcard/"+fname+".txt";

               br = new BufferedReader(new FileReader(fpath));
               String line = "";
               while ((line = br.readLine()) != null) {
                   output.append(line +"\n");
               }
               response = output.toString();

           } catch (IOException e) {
               e.printStackTrace();
               return null;

           }
           return response;

    }
}


class MyFile {
	 
    String TAG = "MyFile";
    Context context;
    public MyFile(Context context)
    {
        this.context = context;
    }
     
    public Boolean writeToSD(String text)
    {
        Boolean write_successful = false;
         File root=null;  
            try {  
                // check for SDcard   
                root = Environment.getExternalStorageDirectory();  
                Log.i(TAG,"path.." +root.getAbsolutePath());  
       
                //check sdcard permission  
                if (root.canWrite()){  
                    File fileDir = new File(root.getAbsolutePath());  
                    fileDir.mkdirs();  
       
                    File file= new File(fileDir, "samplefile.txt");  
                    FileWriter filewriter = new FileWriter(file);  
                    BufferedWriter out = new BufferedWriter(filewriter);  
                    out.write(text);  
                    out.close();  
                    write_successful = true;
                }  
            } catch (IOException e) {  
                Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
                write_successful = false;
            }  
        return write_successful;
    }
     
    public String readFromSD()
    {
        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(sdcard,"samplefile.txt");
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
        }
        return text.toString();
    }
 
   
}