package me.ivysaur.ncdcinstaller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity {

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void onStart() {
		super.onStart();
		
		prepare();
	}

	//
	//
	//
	
	/**
	 * Ref http://stackoverflow.com/a/2879403
	 * 
	 * @param intent
	 * @return boolean Whether the intent can be called
	 */
	private boolean isCallable(Intent intent) {
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 
            PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
	}
	
	public String getNcdcPath() {
		return getFilesDir().getPath() + "/ncdc";
	}
	
	public void prepare() {

		TextView txStatus = (TextView) findViewById(R.id.txStatus);
		Button btLaunch = (Button) findViewById(R.id.btLaunch);
		
		// Reset to default state
		
		txStatus.setText("Loading...");
		btLaunch.setVisibility(View.INVISIBLE);
		btLaunch.setEnabled(true);
		
		// Ensure binary exists
		
		txStatus.setText("Checking ncdc binary...");
		
		File f = new File(getNcdcPath());
		if (! f.exists()) {
			txStatus.setText("Unpacking ncdc...");
			
			InputStream src = getResources().openRawResource(R.raw.ncdc);
			OutputStream dest = null;
			
			try {
				dest = openFileOutput("ncdc", Context.MODE_WORLD_READABLE);
			} catch (FileNotFoundException e) {
				txStatus.setText("Absurd failure");
				return;
			}
			
			// Copy the two streams
			try {
				byte[] buffer = new byte[src.available()];
				src.read(buffer);
				src.close();			
				dest.write(buffer);
				dest.close();
			} catch (IOException e) {
				txStatus.setText("File copy failure");
				return;
			}
			
		}
		
		// Ensure binary is chmod 755.		
		// There's a File.canExecute() but it's apparently best-effort i.e. useless, so always set this.
		
		if (! f.setExecutable(true, false)) {
			txStatus.setText("Error applying +x");
			return;
		}
		
		// Allow launch
		
		txStatus.setText("Ready.");
		btLaunch.setVisibility(View.VISIBLE);
	}
	
	public void btLaunch_onClick(View v) {
		
		TextView txStatus = (TextView) findViewById(R.id.txStatus);
		Button btLaunch = (Button) findViewById(R.id.btLaunch);
		
		txStatus.setText("Launching...");
		btLaunch.setEnabled(false);
		
		// Commandline
		
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		String command = "HOME="+sdcard+"/ NCDC_DIR="+sdcard+"/.ncdc "+getNcdcPath()+" ; exit";
		
		// Create terminal emulator intent
				
		Intent i = new Intent("jackpal.androidterm.RUN_SCRIPT");
		i.addCategory(Intent.CATEGORY_DEFAULT);
		i.putExtra("jackpal.androidterm.iInitialCommand", command);
		
		// Check if intent is satisfied	
		
		if (! isCallable(i)) {
			txStatus.setText("Terminal emulator not available!");
			return;
		}
		
		// Launch intent
		
		txStatus.setText("Launching...");
		startActivity(i);
	}
	
}
