using System;
using System.Collections;
using System.IO;

namespace Hanna.TextSettings
{
	internal class TextSettingsFile 
	{
		private string _path = string.Empty;

		internal TextSettingsFile(string FilePath) 
		{
			_path = FilePath;
		}
		
		internal Hashtable Load()
		{
			Hashtable rtn = new Hashtable();
			if ( File.Exists(_path) )
			{
				StreamReader rdr = new StreamReader(_path);
				string line = string.Empty;

				while ( rdr.Peek() >= 0 )
				{
					line = rdr.ReadLine();
					if ( line != string.Empty )
					{
						string[] fields = line.Split(Constants.TextSettingFieldDelimiter);
						SettingTypes sType = (SettingTypes)Enum.Parse(typeof(SettingTypes),fields[Constants.TextSettingFieldType]);
						TextSetting ts = new TextSetting(sType, 
							fields[Constants.TextSettingFieldSection], 
							fields[Constants.TextSettingFieldName], 
							fields[Constants.TextSettingFieldValue]);
						rtn.Add(ts.Key, ts);								
					}
				}
				rdr.Close();
			}
			return rtn;
		}
		internal void Save(Hashtable TextSettings)
		{
			StreamWriter write = new StreamWriter(_path, false);
			foreach ( TextSetting ts in TextSettings.Values )
			{
				string outStr = string.Empty;
				outStr += ts.SettingType.ToString() + Constants.TextSettingFieldDelimiter;
				outStr += ts.Section + Constants.TextSettingFieldDelimiter;
				outStr += ts.Name + Constants.TextSettingFieldDelimiter;
				outStr += ts.Value + Constants.TextSettingFieldDelimiter;
				write.WriteLine(outStr);
			}
			write.Flush();
			write.Close();
		}
	}
}
