using UnityEngine;
using System.Collections;

public class s_Tongue : MonoBehaviour
{
	public Vector3 direction;
	public Vector3 flyPos;
	
	float speed = 12.0f;
	bool forward = true;
	GameObject player;
	float yPos;
	float playerYPos;
	float distanceTolerance = 1.0f; //This is very important
	
	Vector3 orgScale;
	
	// Use this for initialization
	void Start ()
	{
		orgScale = transform.localScale;
		player = GameObject.Find("Player");
		yPos = transform.position.y;
		playerYPos = player.transform.position.y;
	}
	
	// Update is called once per frame
	void Update ()
	{
		if (renderer.enabled)
		{	
			//Locks their y values
			transform.position = new Vector3(transform.position.x, yPos, transform.position.z);
			player.transform.position = new Vector3(player.transform.position.x, playerYPos, player.transform.position.z);
			
			if (forward)
			{
				//Move forward
				transform.position += (direction * Time.deltaTime * speed) / 1.5f;
				transform.localScale += (direction * Time.deltaTime * speed);
			}
			else
			{
				//Move back
				float distance = Vector3.Distance(player.transform.position, flyPos);
				
				if(distance > distanceTolerance)
				{
					
					transform.parent = null;
					transform.position += (direction * Time.deltaTime * speed / 5) * 5;
					player.transform.position += (direction * Time.deltaTime * speed / 5) * 10;
					transform.localScale -= direction * Time.deltaTime * speed / 5;
				}
				else
				{
					//Reset transforms, parents, update positions
					renderer.enabled = false;
					transform.parent = player.transform;
					player.transform.position = new Vector3(flyPos.x, playerYPos, flyPos.z);
					transform.localScale = orgScale;
					transform.position = new Vector3(player.transform.position.x, yPos, player.transform.position.z);
					forward = true;
					
					s_Player playerScript = player.GetComponent<s_Player>();
					playerScript.usingTongue = false;
					playerScript.moving = false;
					StartCoroutine(playerScript.CheckLose());
					++s_Player.turn;
				}
			}
		}
	}
	
	void OnTriggerStay(Collider other)
	{
		if (other.gameObject.tag == "Fly" && renderer.enabled)
		{
			if (forward)
			{
				flyPos = other.gameObject.transform.position; //Update if you hit a fly before
				direction = Vector3.Normalize(flyPos - transform.position);
				AudioManager.PlaySound(AudioManager.tongueIn);
				forward = false;
			}
		}
	}
}