using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WorldOfPeacecraft
{
	public class ChatInputBox : TextBox
	{
		private LinkedList<string> InputHistory = new LinkedList<string>();
		private LinkedListNode<string> CurrentHistoryEntry;

		public delegate void ChatMessageSubmittedEventHandler (string message);
		public event ChatMessageSubmittedEventHandler ChatMessageSubmitted;

		public ChatInputBox ()
		{
			this.KeyDown += KeyDownEvent;
			this.KeyPress += KeyPressEvent;
		}

		private void KeyPressEvent (object o, KeyPressEventArgs args)
		{
			// Supress the "ding"-sound
			if (args.KeyChar == (char)Keys.Return) {
				args.Handled = true;
			}
		}

		private void KeyDownEvent (object o, KeyEventArgs args)
		{
			if (args.KeyCode == Keys.Return) {
				if (this.Text != "") {
					string message = this.Text;
					this.Text = "";
					if (CurrentHistoryEntry == null) {
						InputHistory.AddLast (message);
					} else {
						CurrentHistoryEntry.Value = message;
						CurrentHistoryEntry = null;
					}
					if (ChatMessageSubmitted != null) {
						this.ChatMessageSubmitted (message);
					}
				}
				args.Handled = true;
			} else if (args.KeyCode == Keys.Up) {
				if (InputHistory.Count > 0) {
					if (CurrentHistoryEntry == null) {
						CurrentHistoryEntry = InputHistory.Last;
						if (this.Text != "") {
							InputHistory.AddLast (this.Text);
						}
						this.Text = CurrentHistoryEntry.Value;
						args.Handled = true;
					} else {
						if (CurrentHistoryEntry != InputHistory.First) {
							CurrentHistoryEntry.Value = this.Text;
							CurrentHistoryEntry = CurrentHistoryEntry.Previous;
							this.Text = CurrentHistoryEntry.Value;
							args.Handled = true;
						}
					}
				}
			} else if (args.KeyCode == Keys.Down) {
				if (CurrentHistoryEntry != null) {
					CurrentHistoryEntry.Value = this.Text;
					CurrentHistoryEntry = CurrentHistoryEntry.Next;
					if (CurrentHistoryEntry == null) {
						this.Text = "";
					} else {
						this.Text = CurrentHistoryEntry.Value;
					}
				}
			} else if (args.KeyCode == Keys.Escape) {
				((Gui)this.Parent.Parent).FocusMap();
				args.Handled = true;
			}
		}
	}

}
