using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

public class CommandLine : MonoBehaviour
{
	//public static event Action<string> OnCommand;

	[SerializeField]
	InputField input;

	[SerializeField]
	Text inputPrefix;

	[SerializeField]
	Text history;

	string[] rawHistory;
	int historyIndex;
	int currentHistoryIndex;

	public void Init(string playerName)
	{
		rawHistory = new string[20000];
		currentHistoryIndex = historyIndex = 0;

		input.onEndEdit.AddListener(t => Focus());

		Focus();

		inputPrefix.text = playerName;

		transform.parent.gameObject.SetActive(true);
	}

	void LateUpdate()
	{
		if(!input.isFocused)
		{
			Focus();
		}

		if(Input.GetKeyDown(KeyCode.UpArrow))
		{
			if(currentHistoryIndex == 0)
				return;

			--currentHistoryIndex;

			input.text = rawHistory[currentHistoryIndex];
			input.MoveTextEnd(false);
		}
		else if(Input.GetKeyDown(KeyCode.DownArrow))
		{
			if(currentHistoryIndex == 199)
				return;

			++currentHistoryIndex;

			input.text = rawHistory[currentHistoryIndex];
			input.MoveTextEnd(false);
		}

		if(Input.GetKeyDown(KeyCode.Return))
		{
			var t = input.text;

			if(string.IsNullOrEmpty(t))
				return;

			if(historyIndex >= 20000 - 1)
			{
				historyIndex = 0;
			}

			history.text += "\n" + t;
			rawHistory[historyIndex] = t;
			input.text = "";

			currentHistoryIndex = ++historyIndex;

			Focus();

			//if(OnCommand != null)
				//OnCommand(t);

			Game.CurrentGame.AddInput(new CommandInput
			{
				playerId = Game.CurrentGame.myPlayerId,
				input = t
			});
		}
	}

	void Focus()
	{
		//var dummyData = new BaseEventData(EventSystem.current);
		var dummyClick = new PointerEventData(EventSystem.current);

		//EventSystem.current.SetSelectedGameObject(input.gameObject, dummyData);
		input.OnPointerClick(dummyClick);
		input.MoveTextEnd(false);
	}
}
