using UnityEngine;
using System.Collections;

public class CookieButton : MonoBehaviour {

	public bool moving = false;

	public bool deadlyButton = false;
	public bool friendlyButton = false;

	public Lever lever;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.I)){
			ActivateButton();
		}
	}

	void ActivateButton(){
		//StartCoroutine(Translation(transform,transform.position,new Vector3(transform.position.x+1,transform.position.y,transform.position.z),1f));
		if(!moving){
			moving = true;
			StartCoroutine(Translation(transform,transform.position,transform.parent.position,1f));
			Debug.Log("Cookie button");
		}
	}

	/*void OnTriggerEnter(Collider col)
	{
		Debug.Log("TRIGGER ENTER " + col.gameObject.name);
		if(col.gameObject.tag == "Player")
		{
			Debug.Log("BUTTON ACTIVE");
			ActivateButton();
		}
	}*/

	public GameObject thingToEvillyRotate;

	void OnCollisionEnter(Collision col)
	{
		Debug.Log("COLLISION ENTER " + col.gameObject.name);
		if(col.gameObject.tag == "Player")
		{
			Debug.Log("BUTTON ACTIVE");
			ActivateButton();
			if(deadlyButton){
				Debug.Log("I AM THE BUTTON OF DEATH");
				StartCoroutine(Rotation(thingToEvillyRotate.transform,new Vector3(-80f,0f,0f),0.3f));
			}
			if(friendlyButton){
				if(lever != null){
					Debug.Log("ENABLING THE LEVER");	
				}
			}
		}

	}
	
	enum MoveType {Time, Speed}
	
	public IEnumerator Translation (Transform thisTransform, Vector3 startPos, Vector3 endPos, float value){
		float rate = 1f/value;
		float t = 0.0f;
		while (t < 1.0) {
			t += Time.deltaTime * rate;
			thisTransform.position = Vector3.Lerp(startPos, endPos, t);
			yield return null; 
		}
		while (t > 0.0) {
			t -= Time.deltaTime * rate;
			thisTransform.position = Vector3.Lerp(startPos, endPos, t);
			yield return null; 
		}
		moving = false;
	}

	public IEnumerator Rotation (Transform thisTransform, Vector3 degrees, float time) {
		Quaternion startRotation = thisTransform.rotation;
		Quaternion endRotation = thisTransform.rotation * Quaternion.Euler(degrees);
		double rate = 1.0/time;
		double t = 0.0;
		while (t < 1.0) {
			t += Time.deltaTime * rate;
			thisTransform.rotation = Quaternion.Slerp(startRotation, endRotation, (float)t);
			yield return null;
		}
	}
}
