/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.me.androiddemo;

import android.app.Activity;
import android.os.Bundle;
import android.content.Context;


import org.library.*;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.File;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.AlertDialog;
import android.widget.Toast;

/**
 *
 * @author Spartacus Rex
 */
public class MainActivity extends Activity {



	public void alert(String output) {

		AlertDialog alert;

		alert = new AlertDialog.Builder(this).create();

		alert.setMessage(output);

		alert.show();

	}
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // ToDo add your GUI initialization code here
        setContentView(R.layout.main);
	

		Context context = getApplicationContext();

		String localPath = "/data/data/org.me.androiddemo/"; 
		
		String local = localPath + "arm-picoLisp.tar.gz";

		if (!new File(localPath + "busybox").exists()) {
			Toast.makeText(context, "Downloading busybox", Toast.LENGTH_SHORT).show();
			download("http://dl.dropbox.com/u/20783971/busybox", localPath + "busybox");
			exec("/system/bin/chmod 744 " + localPath + "busybox");
		}

		if (!new File(local).exists()) {
			Toast.makeText(context, "Downloading picoLisp", Toast.LENGTH_SHORT).show();
			download("http://dl.dropbox.com/u/20783971/arm-picoLisp.tar.gz", local);
			exec(localPath + "busybox tar -zxvf " + local + " -C " + localPath);
		}

		//String output = exec("/system/bin/ls /data/data/org.me.androiddemo/arm-picoLisp");
		//alert(output);

		exec(localPath + "busybox killall -9 picolisp");



	Toast.makeText(context, "Starting App", Toast.LENGTH_SHORT).show();

		execAsync(localPath + "arm-picoLisp/pil @lib/http.l @lib/xhtml.l " + localPath + "arm-picoLisp/s.l", localPath + "arm-picoLisp");

		try {
				Thread.sleep(1000);
		}  catch (InterruptedException e) {
		}
		WebView mWebView;

		mWebView = (WebView) findViewById(R.id.webview);

		mWebView.getSettings().setJavaScriptEnabled(true);

		mWebView.setWebViewClient(new WebViewClient() {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			view.loadUrl(url);

			return true;

		}

	});
		mWebView.loadUrl("http://127.0.0.1:8001/");
    }
	// Executes UNIX command.
    private void execAsync(String command, String dir) {
        try {
            Process process = Runtime.getRuntime().exec(command, null, new File(dir));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
	// Executes UNIX command.
    private String exec(String command) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            int read;
            char[] buffer = new char[4096];
            StringBuffer output = new StringBuffer();
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            reader.close();
            process.waitFor();
            return output.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    
    private void download(String urlStr, String localPath) {
    	try {
			URL url = new URL(urlStr);
			HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
			urlconn.setRequestMethod("GET");
			urlconn.setInstanceFollowRedirects(true);
			urlconn.connect();
			InputStream in = urlconn.getInputStream();
			FileOutputStream out = new FileOutputStream(localPath);
			int read;
			byte[] buffer = new byte[4096];
			while ((read = in.read(buffer)) > 0) {
				out.write(buffer, 0, read);
			}
			out.close();
			in.close();
			urlconn.disconnect();
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
    }

}
