#pragma strict

class ConfigFile
{
	private var m_data:Hashtable;
	static function Create(_file:String):ConfigFile
	{
		var data:TextAsset = Resources.Load(_file, TextAsset);
		if (data != null)
			return new ConfigFile(data);
		else
			return null;
	}

	function GetSetting(_key:String, _section:String):String
	{
		if (m_data == null)
			return "";
		
		var setting:Hashtable = m_data[_section] as Hashtable;
		if (setting == null)
			return "";
		if (setting.ContainsKey(_key))
			return setting[_key] as String;
		else
			return "";
	}
	
	function GetKeys(_section:String):String[]
	{
		if (m_data == null)
			return null;
		var setting:Hashtable = m_data[_section] as Hashtable;
		if (setting == null)
			return null;
		
		var arr = new Array ();
		var ie = setting.Keys.GetEnumerator();
		while(ie.MoveNext())
		{
			arr.Add(ie.Current);
			//Debug.Log(ie.Current.ToString());
		}
		
		var ret:String[] = arr.ToBuiltin(String) as String[];
		return ret;
	}
	
	function GetValues(_section:String):String[]
	{
		if (m_data == null)
			return null;
		
		var setting:Hashtable = m_data[_section] as Hashtable;
		if (setting == null)
			return null;

		var arr = new Array ();
		var ie = setting.Values.GetEnumerator();
		while(ie.MoveNext())
		{
			arr.Add(ie.Current);
		}
		
		var ret:String[] = arr.ToBuiltin(String) as String[];
		return ret;
	}
	
	private function ConfigFile(_data:TextAsset)
	{
		m_data = new Hashtable();
		
		var auto_key_idx:int;
		var section:String;
		var settings:Hashtable;
		
		var lines = _data.text.Split('\n'[0]);
		for (var line in lines)
		{
			if (line.Length <= 0 || line[0] == "#"[0] || line[0] == "@"[0])
				continue;
			
			if (line[0] == "["[0] && line[line.Length-1] == "]"[0])
			{
				section = line.Substring(1, line.Length-2);
				settings = m_data[section] as Hashtable;
				if (settings == null)
				{
					settings = new Hashtable();
					m_data.Add(section, settings);
				}
			}
			else
			{
				var seperator_pos = line.IndexOf("=");
				if (seperator_pos > 0)
				{
					var key:String = line.Substring(0, seperator_pos);
					var val:String = line.Substring(seperator_pos+1);
					key.Trim([" "[0], "\t"[0]]);
					val.Trim([" "[0], "\t"[0]]);
					settings.Add(key, val);
				}
				else
				{
					auto_key_idx++;
					settings.Add(auto_key_idx.ToString(), line);
				}
			}
		}
	}
}