package com.example.neticaj_android_demo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.res.AssetManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupNeticaDemo();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void setupNeticaDemo(){         
    	System.out.println("########## Starting Main Activity");   
    	//System.out.println("getExternalStorageDirectory () =" + Environment.getExternalStorageDirectory().getAbsolutePath() );
    	AssetManager am = getAssets(); 
		File appContextFileDir = getApplicationContext().getFilesDir(); 
		final String localPath = appContextFileDir.getPath();
		System.out.println("getApplicationContext.getFilesDir() =" + localPath );
		//copies the contents of the DATA_IN directory in your assets/ folder to 
		//a read/writeable area "[localPath]/DATA_IN" that your app can access using regular java File i/o
		final String  localDirName = "DATA_IN";
		copyFilesFromAssetManagerToNewDir( am, appContextFileDir, localDirName ); 
    	
    	final Button button1 = (Button)   findViewById(R.id.button1);         
    	final TextView textview1 = (TextView) findViewById(R.id.textView1);         
    	button1.setOnClickListener(new View.OnClickListener() {             
    		public void onClick(View v) {                 
    			// Perform action on click      
    			System.out.println("########### Button Clicked ");
		        Thread myThread = new Thread(){ 
		            public void run(){ 
		            	Demo demo = new Demo(); 
						try {
							String output = demo.run(localPath + "/" + localDirName);
			    			textview1.setText( output );    
						} catch (Exception e) { 
							e.printStackTrace();
			    			textview1.setText( e.getMessage() );    
						}   
		            } 
		        }; 
		     
		        myThread.run();  
    		}         
    	});  
}
    private String readTextFile(InputStream inputStream){
    	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    	byte buf[] = new byte[1024];
    	int len;
    	try{
    		while ((len = inputStream.read(buf)) != -1){
    			outputStream.write(buf,0,len);
    		}
    		outputStream.close();
    		inputStream.close();
    	} catch (IOException e){ 
    		e.printStackTrace();
    	}
    	return outputStream.toString();
    }
    
    private void copyFilesFromAssetManagerToNewDir( AssetManager am, File toDir, String newDirName ){
	    try {
			(new File( toDir.toString() + "/" + newDirName)).mkdirs(); //first create the newDir
	        System.out.println("---------- "+ newDirName); 
			String[] list = am.list(newDirName);
			for (int i=0; i<list.length; i++){
				System.out.println("file["+i+"]=" + list[i] );
				try {
					InputStream is = am.open( newDirName + "/" + list[i] , AssetManager.ACCESS_BUFFER);
				 	String fullPath = toDir.toString() + "/" + newDirName + "/" + list[i];
					FileOutputStream fos = new FileOutputStream( fullPath ); 
					copyInputStreamToOutputStream(is,fos);  
			     }
			    catch (Exception e2){
			    	System.out.println("... skipping " + list[i] ); //ignore subdirectories
			    }
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}

    /*
     * Copy all of is to os, and close streams.
     */
    static final int BUFF_SIZE = 100000;
    static final byte[] buffer = new byte[BUFF_SIZE];
    private void copyInputStreamToOutputStream( InputStream is, OutputStream os )throws IOException{
        try {
	        while (true) {
	            synchronized (buffer) {
	               int amountRead = is.read(buffer);
	               if (amountRead == -1) {
	                  break;
	               }
	               //System.out.println("amountRead="+ amountRead); 
	               os.write(buffer, 0, amountRead); 
	               
	            }
	         } 
        } finally {
            if (is != null) {
               is.close();
            }
            if (os != null) {
               os.close();
            }
         }
    }
 

}


