package r.e;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import re.anywhere.confedit.ReadConfig;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

public class config extends Activity {


	public EditText editbox;
	public Button savebutton;
	boolean firstrun=false;
	public static String configFileName = "/sdcard/t.conf";
	public static String configFileName2 = "/data/data/r.e/robot.conf";
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		

		setContentView(R.layout.confedit);
		editbox = (EditText) findViewById(R.id.EditTextC1);
		showKeyboard();
		savebutton = (Button) findViewById(R.id.ButtonC1 );
		savebutton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (saveFile())
					nuketheapp();
			}
		});
//		showKeyboard();
//		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		ReadConfig.readfile();
//		showKeyboard();
		configFileName = ReadConfig.getstring("file1", configFileName);
		configFileName2 = ReadConfig.getstring("file2", configFileName2);
//		showKeyboard();
		loadFile();
//		showKeyboard();

	}

	private void showKeyboard() {
		InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		mgr.showSoftInput(editbox, InputMethodManager.SHOW_FORCED);
		mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);	                      
	}		


	public boolean loadFile()
	{
		savebutton.setText("CLICK HERE TO SAVE AND EXIT ("+configFileName+")");
		File checkthisfile = new File(configFileName);
		String full = "www.robots-everywhere.com/re_wiki/\n#See the robotseverywhere wiki for explanation\n#and to download other utilities\n\n" +
		        "mailuser=a.data.logger@gmail.com" +
		        "mailpass=derp\n" +
		        "ftphost=www.robots-everywhere.com\n" +
		        "ftpuser=a.data.logger\n" +
		        "ftppass=log\n" +
		        "\n\n" +
				"desc0=ADC 0\n" +
				"mult0=5000\n" +
				"div0=65535\n" +
				"unit0=mV\n" +
				"desc1=ADC 1\n" +
				"mult1=5000\n" +
				"div1=65535\n" +
				"unit1=mV\n" +
				"desc2=ADC 2\n" +
				"mult2=5000\n" +
				"div2=65535\n" +
				"unit2=mV\n" +
				"";

		
		if (checkthisfile.exists() == false)
		{
			checkthisfile = new File(configFileName2);
			savebutton.setText("CLICK HERE TO SAVE AND EXIT ("+configFileName2+")");
		}
		if(checkthisfile.exists() && checkthisfile.isFile())
		{
			try
			{
				full="";
				BufferedReader idreader = new BufferedReader(new FileReader(checkthisfile));
				String temp = null;
				do
				{
					temp = idreader.readLine();
					if (temp != null)
						if (temp != "null")
							full = full + temp + "\n";
				}
				while (temp != null);
				idreader.close();
				idreader = null;
			}
			catch(FileNotFoundException e)
			{
				Log.e("config", "ID File Not Found");
				editbox.setText(full);
				return false;
			}
			catch(IOException e)
			{
				Log.e("config", "Bad ID File");
				editbox.setText(full);
				return false;
			}
			Log.i("config", "ID file loaded");
			editbox.setText(full);
			return true;
		}
		else
			firstrun=true; // probable first run, so on exit, go directly to the main app
		editbox.setText(full);
		return false;
	}


	private boolean saveFile(){ // try to save in both locations, can also be used to quickly sync with a roaming sd card
		try {
			FileWriter fstream;
			fstream = new FileWriter(configFileName);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(editbox.getText().toString());
			out.close();
			fstream.close();
			Runtime.getRuntime().exec(new String[] { "sh", "-c", "chmod 666 "+configFileName });
			Log.i("config", "ID file saved at" + configFileName);
		} catch (IOException e) {e.printStackTrace();}

		try {
			FileWriter fstream;
			fstream = new FileWriter(configFileName2);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(editbox.getText().toString());
			out.close();
			fstream.close();
			Runtime.getRuntime().exec(new String[] { "sh", "-c", "chmod 666 "+configFileName2 });
			Log.i("config", "ID file saved at" + configFileName2);
			return true;
		} catch (IOException e1) {e1.printStackTrace();		} 
		return false;
	}

	private void nuketheapp()
	{
		/*
		ExecByBatch.GenerateExecutionFile(this.getFilesDir().getAbsolutePath());
		ExecByBatch.RunCommand("chmod 777 /"+getCacheDir().getAbsolutePath()+"/..");
		ExecByBatch.RunLoop();
		if (firstrun)
			ExecByBatch.RunAct(RobotClient.maintaskname);
		android.os.Process.killProcess(android.os.Process.myPid()); // NUKE
		*/
//		adcdemo.RunAct(adcdemo.maintaskname);
		this.finish();
	}



	public boolean onCreateOptionsMenu(Menu menu) {
		// these show up in the primary screen: out of order for display reasons
		menu.add(0, 0, 0, "(!) QUIT (!)");
		return true;
	}
	public boolean onPrepareOptionsMenu(Menu menu) {
		nuketheapp();
		return true;
	}


};




