package re.anywhere.confedit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import r.t.config;


/* example usage
	    ReadConfig.configFileName = "/sdcard/robot.conf"; 
	    ReadConfig.configFileName2 = "/data/data/re.anywhere.confedit/robot.conf";
  		ReadConfig.readfile(); 
		idString=ReadConfig.getstring("id","0");
		fullscreen=ReadConfig.getboolean("fullscreen",false);
		headingadjust=(int) ReadConfig.getint("compassfix", 0);
		serialportbaud=(int) ReadConfig.getint("serialbaud",57600);
		reschar=ReadConfig.getstring("resolution","r").toUpperCase().charAt(0);
		serialportname=ReadConfig.getstring("serialport","/dev/ttyMSM2");
		bluetoothMAC=ReadConfig.getstring("bluetooth","").toUpperCase();
 */

public class ReadConfig {

	// why two: 
	static public String configFileName = config.configFileName; 
	static public String configFileName2 = config.configFileName2;
	static public HashMap<String, String> configuration = new HashMap<String, String>();// identifier
	static public boolean initialized=false;
	static private String temp = " ";

	static public final int readfile() {
		initialized=false;
		File checkthisfile = new File(configFileName);
		if (checkthisfile.exists() == false)
			checkthisfile = new File(configFileName2);
		if (checkthisfile.exists() && checkthisfile.isFile()) {
			try {
				FileReader freader = new FileReader(checkthisfile);
				BufferedReader idreader = new BufferedReader(freader,2048);
				initialized=true;
				do {
					boolean good = true; // assume a good option
					temp = idreader.readLine();
					if (temp != null && temp.contains("=")) {
						String[] line = temp.split("\\s*=\\s*"); // eat whitespace
						// we need to set some pre-defined config options, the rest go into the HashMap
						if (line[0].toLowerCase().startsWith("ip")) // allows for serverip2, serverip3.... set server IP, again important
						{
							if (!line[1].matches("\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?.\\d\\d?\\d?"))
							{
								good = false;
							}
						}
						if (line.length != 2)
							good=false;
						if (good)
						{
							//Log.i("RobotClient_RobotClient_Config",line[0]+"="+line[1]);
							configuration.put(line[0].toLowerCase(), line[1]); // just add it to configuration so ti can be used (or not) later; ignore garbage
						}
					}
				} while (temp != null);
				idreader.close();
				freader.close();
				System.gc();
			} catch (FileNotFoundException e) {
				return -1;
			} catch (IOException e) {
				return -2;
			}
			return 0;
		}
		return -3;
	}

	static public boolean getboolean(String key,boolean def)
	{
		if (initialized==false)
			if (readfile() < 0)
				return def;
		temp = configuration.get(key); 
		if (temp != null)
			try{return Boolean.parseBoolean(temp.trim());} catch (Exception e){return def;};
			return def;
	}
	static public String getstring(String key,String def)
	{
		if (initialized==false)
			if (readfile() < 0)
				return def;
		temp = configuration.get(key); 
		if (temp != null)
			try{return temp.trim();} catch (Exception e){return def;};
			return def;
	}
	static public long getint(String key,long def)
	{
		if (initialized==false)
			if (readfile() < 0)
				return def;
		temp = configuration.get(key); 
		if (temp != null)
			try{return Integer.parseInt(temp.trim());} catch (Exception e){return def;};
			return def;
	}
	static public double getreal(String key,double def)
	{
		if (initialized==false)
			if (readfile() < 0)
				return def;
		temp = configuration.get(key); 
		if (temp != null)
			try{return Double.parseDouble(temp.trim());} catch (Exception e){return def;};
			return def;
	}

	   public static String readFileAsString(String filePath)
			    throws java.io.IOException{
			        StringBuffer fileData = new StringBuffer(1000);
			        BufferedReader reader = new BufferedReader(new FileReader(filePath),8192);
			        char[] buf = new char[1024];
			        int numRead=0;
			        while((numRead=reader.read(buf)) != -1){
			            String readData = String.valueOf(buf, 0, numRead);
			            fileData.append(readData);
			            buf = new char[1024];
			        }
			        reader.close();
			        return fileData.toString();
			    }

}
