/*
 * Paraselene
 * Copyright (c) 2009, 2010  Akira Terasaki
 * このファイルは同梱されているLicense.txtに定めた条件に同意できる場合にのみ
 * 利用可能です。
 */
package paraselene.mockup;

import java.io.*;
import java.util.*;

class Config {
	static final String	CONFIG = "paraselene.cfg";
	private static HashMap<File, File>	loaded = new HashMap<File, File>();
	private static final char NULL_CHAR = ' ';

	private static StringBuilder add( ArrayList<String> list, StringBuilder org ) {
		String[]	data = org.toString().split( "\\p{Space}" );
		for ( int i = 0; i < data.length; i++ ) {
			data[i] = data[i].trim();
			if ( data[i].isEmpty() )	continue;
			list.add( data[i] );
		}
		return new StringBuilder();
	}

	private static ArrayList<String> parse( String org ) {
		ArrayList<String>	ret = new ArrayList<String>();
		org = org.trim();
		if ( org.isEmpty() )	return ret;
		char[]	dim = org.toCharArray();
		char	deli = NULL_CHAR;
//		int	start = 0;
		StringBuilder	out = new StringBuilder();

		for ( int i = 0; i < dim.length; i++ ) {
			if ( deli == NULL_CHAR ) {
				if ( dim[i] == '\\' ) {
					i++;
					if ( i >= dim.length )	break;
					out = out.append( dim[i] );
					continue;
				}
				if ( dim[i] == '\'' || dim[i] == '"' ) {
//					start = i + 1;
					deli = dim[i];
					out = add( ret, out );
					continue;
				}
				out = out.append( dim[i] );
				continue;
			}
			out = add( ret, out );
			if ( deli != NULL_CHAR ) {
				StringBuilder	buf = new StringBuilder();
				for ( ; i < dim.length; i++ ) {
					if ( dim[i] == '\\' ) {
						i++;
						if ( i >= dim.length )	break;
						buf = buf.append( dim[i] );
						continue;
					}
					if ( dim[i] == deli )	break;
					buf = buf.append( dim[i] );
				}
				ret.add( buf.toString() );
				deli = NULL_CHAR;
			}
		}
		add( ret, out );
		return ret;
	}

	static void load( File file ) throws Exception {
		if ( loaded.put( file, file ) != null )	return;
		BufferedReader	br = new BufferedReader( new FileReader( file ) );
		ArrayList<String>	list = new ArrayList<String>();
		while( true ) {
			String	str = br.readLine();
			if ( str == null )	break;
			list.addAll( parse( str ) );
		}
		br.close();
		Param.setParam( list.toArray( new String[0] ) );
	}
}

