using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class InsertKey : MonoBehaviour
{
	public Text textKey1, textKey2;
		
	public bool inserting = false;
	
	public bool firstDone = false;
	public Animator key1Animator;
	public bool secondDone = false;
	public Animator key2Animator;

	static string[] disableKeys = new string[] { "H", "C", "S", "M", "X" };

	public void Show()
	{
		do
		{
			textKey1.text = "" + (char)Random.Range('A', 'Z');
		} while (System.Array.IndexOf(disableKeys, textKey1.text) >= 0);

		do
		{
			textKey2.text = "" + (char)Random.Range('A', 'Z');
		} while (System.Array.IndexOf(disableKeys, textKey2.text) >= 0 || textKey2.text == textKey1.text);

		GetComponent<Animator>().Play("enter");
		inserting = true;

		firstDone = false;
		key1Animator.Play("keyrestore");

		secondDone = false;
		key2Animator.Play("keyrestore");
	}

	public void Hide()
	{
		inserting = false;
		GetComponent<Animator>().Play("exit");
	}

	void Update()
	{
		if (!inserting)
			return;

		KeyCode c1 = (KeyCode)((int)KeyCode.A + (textKey1.text[0] - 'A'));
		KeyCode c2 = (KeyCode)((int)KeyCode.A + (textKey2.text[0] - 'A'));
		
		if (Input.GetKeyDown(c1))
		{
			firstDone = true;
			key1Animator.Play("keyinsert");
		}
		
		if (Input.GetKeyDown(c2))
		{
			secondDone = true;
			key2Animator.Play("keyinsert");
		}

		if (firstDone && secondDone)
		{
			inserting = false;

			Invoke("StartLaunchAndHide", 0.5f);
		}

		if (!firstDone)
			key1Animator.Play("keyrestore");
		if (!secondDone)
			key2Animator.Play("keyrestore");
	}

	void StartLaunchAndHide()
	{
		Player.LocalPlayer.Confirm();
		Hide();
	}
}
