// Copyright (C) 2003 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2005 panacoran <panacoran@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: ConfigFile.cs,v 1.2 2007-12-27 08:34:39 panacoran Exp $

using System;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;

namespace Protra.Lib.Config
{
	/// <summary>
	/// 設定ファイルを読み書きする。
	/// </summary>
	public class ConfigFile
	{
		private Hashtable hash = new Hashtable();
		private string filename;

		/// <summary>
		/// コンストラクタ
		/// </summary>
		/// <param name="configName"></param>
		public ConfigFile(string configName)
		{
			filename = Path.Combine(Global.DirConf, configName + ".conf");
		}

		/// <summary>
		/// 設定ファイルを読み込む。
		/// </summary>
		public void Read()
		{
			StreamReader reader = new StreamReader(filename);
			string line;
			Regex regex = new Regex(@"^([^=]+)=(.*)$");
			while ((line = reader.ReadLine()) != null)
			{
				Match m = regex.Match(line);
				if(m.Success)
					hash[m.Groups[1].Value] = m.Groups[2].Value;
			}
			reader.Close();
		}

		/// <summary>
		/// 設定ファイルを書き込む。
		/// </summary>
		public void Write()
		{
			if(! Directory.Exists(Global.DirConf))
				Directory.CreateDirectory(Global.DirConf);
			StreamWriter writer = new StreamWriter(filename);
			ArrayList keys = new ArrayList(hash.Keys);
			keys.Sort();
			foreach(string key in keys)
				if(hash[key] != null)
					writer.WriteLine(key + "=" + (string)hash[key]);
			writer.Close();
		}

		/// <summary>
		/// 設定内容を取得あるいは設定する。
		/// </summary>
		public string this[string key]
		{
			get { return (string)hash[key];  }
			set { hash[key] = value; }
		}
	}
}
