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

namespace KeyConfig.Map
{
	internal static class KeyMapReader
	{
		static Regex rKey = new Regex("(?<key>[^=].*)[=](?<value>.*)");

		internal static KeyMap ReadFrom(string path)
		{
			if (!File.Exists(path))
			{
				return new KeyMap(new Dictionary<string,string>());
			}

			var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
			var sr = new StreamReader(fs, Encoding.GetEncoding("shift-jis"));
			var dic = new Dictionary<string, string>();

			while (sr.Peek() != -1)
			{
				string line = sr.ReadLine();
				Match match;

				if ((match = rKey.Match(line)) != Match.Empty)
				{
					dic.Add(match.Groups["key"].Value, match.Groups["value"].Value);
				}
			}
			return new KeyMap(dic);
		}
	}
}