package org.kered.dko.ant;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.kered.dko.json.JSONException;
import org.kered.dko.json.JSONObject;

class DataSourceGenerator {

	static final String _DEFAULT_PACKAGE_DATASOURCE_LOADER = "_DEFAULT_PACKAGE_DATASOURCE_LOADER";

	public static String getDataSourceName(final String dataSource) {
		if (dataSource == null) return null;
		final String[] x = dataSource.split("=");
		String name = x[0].trim();
		name = name.substring(0, 1).toUpperCase() + name.substring(1);
		return name;
	}

	public static String getClassName(final String dataSource) {
		final String[] x = dataSource.split("=");
		final String cls = x[1].substring(0, x[1].lastIndexOf(".")).trim();
		return cls;
	}

	public static String getMethodName(final String dataSource) {
		final String[] x = dataSource.split("=");
		String method = x[1].substring(x[1].lastIndexOf(".")+1).trim();
		while (method.endsWith("(") || method.endsWith(")") || method.endsWith(" ") || method.endsWith(";")) {
			method = method.substring(0, method.length() - 1);
		}
		return method;
	}

	private static List<String> getSchemaList(final String metadataFile) throws IOException {
		final BufferedReader br = new BufferedReader(new FileReader(metadataFile));
		final StringBuffer sb = new StringBuffer();
		String s = null;
		while ((s=br.readLine())!=null) sb.append(s).append('\n');
		try {
			final JSONObject metadata = new JSONObject(sb.toString());
			final JSONObject schemas = metadata.getJSONObject("schemas");
			return new ArrayList<String>(schemas.keySet());
		} catch (final JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static void go(final String dir, final String pkg, final String dataSource,
			final String metadataFile, final Map<String, String> schemaAliases) throws IOException {
		final String pkgDir = Util.join("/", pkg.split("[.]"));
		new File(Util.join("/", dir, pkgDir)).mkdirs();

		final String name = getDataSourceName(dataSource);
		final String cls = getClassName(dataSource);
		final String method = getMethodName(dataSource);
		final List<String> schemaList = getSchemaList(metadataFile);

		for (String schema : schemaList) {

			if (schemaAliases.containsKey(schema)) {
				schema = schemaAliases.get(schema);
			}

			final String pkgName = ClassGenerator.sanitizeJavaKeywords(schema);

			final File file = new File(Util.join("/", dir, pkgDir, name + ".java"));
			System.out.println("writing: "+ file.getAbsolutePath());

			final BufferedWriter br = new BufferedWriter(new FileWriter(file));

			br.write("package "+ pkg +";\n");
			br.write("\n");
			br.write("import org.kered.dko.Context;\n");
			br.write("import org.kered.dko.datasource.ReflectedDataSource;\n");
			br.write("\n");
			br.write("public class "+ name +" {\n");
			br.write("\n");
			br.write("\n");
			br.write("\tpublic static "+ "ReflectedDataSource" +" "+ "INSTANCE"
					+" = new "+ "ReflectedDataSource" +"(\""+ cls +"\", \""+ method +"\");\n");
			br.write("\n");
			br.write("}\n");

			br.close();

		}

	}

}

@@ -572,16 +572,70 @@
 n null;%0A
+%09%09if (!dataSource.contains(%22=%22)) return %22_DefaultDS%22;%0A
 %09%09final 
@@ -847,34 +847,57 @@
 ce) %7B%0A%09%09
-final String%5B%5D x =
+String part2 = dataSource.contains(%22=%22) ?
  dataSou
@@ -906,24 +906,40 @@
 e.split(%22=%22)
+%5B1%5D : dataSource
 ;%0A%09%09final St
@@ -949,20 +949,21 @@
 g cls = 
-x%5B1%5D
+part2
 .substri
@@ -968,20 +968,21 @@
 ring(0, 
-x%5B1%5D
+part2
 .lastInd
@@ -1083,34 +1083,57 @@
 ce) %7B%0A%09%09
-final String%5B%5D x =
+String part2 = dataSource.contains(%22=%22) ?
  dataSou
@@ -1138,32 +1138,48 @@
 ource.split(%22=%22)
+%5B1%5D : dataSource
 ;%0A%09%09String metho
@@ -1182,20 +1182,21 @@
 ethod = 
-x%5B1%5D
+part2
 .substri
@@ -1202,12 +1202,13 @@
 ing(
-x%5B1%5D
+part2
 .las

removed the need for a variable name for the datasource def