using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using KeyConfig.Config;
using KeyConfig.Map;

namespace KeyConfig
{
	internal class KeyEditor : EditorBase
	{
		//----------// //----------// //----------// //----------//
		//
		//	Fields
		//
		//----------// //----------// //----------// //----------//

		ConfigData config = null;
		KeyMap map = null;
		List<TextBox> textBoxList = new List<TextBox>();

		//----------// //----------// //----------// //----------//
		//
		//	Methods
		//
		//----------// //----------// //----------// //----------//

		internal void InitializeEditor(ConfigData config, KeyMap map, int labelWidth, int textWidth, int labelHeight)
		{
			if (config == null) throw new ArgumentNullException("config");
			if (map == null) throw new ArgumentNullException("map");

			this.config = config;
			this.map = map;

			var lblTitle = new Label()
			{
				AutoSize = true,
				Text = "キーボード用のキーコンフィグ"
			};

			this.Controls.Add(lblTitle);

			var kt = new ListLabel() { Top = 24 };
			kt.UpdateTitle(GetKeyTitles(), 88);

			this.Controls.Add(kt);

			for (int i = 0; i < config.KeyList.Count; i++)
			{
				var textBox = new TextBox()
				{
					ReadOnly = true,
					Multiline = true,
					AcceptsTab = true,
					Left = labelWidth + 8,
					Width = textWidth,
					Top = labelHeight * (i + 1),
					Text = ((Keys)config.KeyList[i].Value).ToString()
				};

				textBox.KeyDown += new KeyEventHandler(txtKey_KeyDown);

				this.Controls.Add(textBox);

				textBoxList.Add(textBox);
			}

			this.Width = textBoxList[textBoxList.Count - 1].Right;
			this.Height = labelHeight * (config.KeyList.Count + 1);
		}

		private void txtKey_KeyDown(object sender, KeyEventArgs e)
		{
			var box = sender as TextBox;
			int index = textBoxList.IndexOf(box);

			box.Text = e.KeyCode.ToString();
			config.KeyList[index] = new KeyValuePair<string, int>(config.KeyList[index].Key, e.KeyValue);

			if (index < (textBoxList.Count - 1))
			{
				textBoxList[index + 1].Focus();
			}
			else
			{
				OnProceedFocus(EventArgs.Empty);
			}
			Edited = true;
		}

		private string GetKeyTitle(int index)
		{
			return map.Parse(config.KeyList[index].Key);
		}

		private List<string> GetKeyTitles()
		{
			var ktt = new List<string>();

			for (int i = 0; i < config.KeyList.Count; i++)
			{
				ktt.Add(GetKeyTitle(i));
			}

			return ktt;
		}

		//----------// //----------// //----------// //----------//
		//
		//	Properties
		//
		//----------// //----------// //----------// //----------//

		internal Control FocusTarget
		{
			get
			{
				return textBoxList[0];
			}
		}
	}
}