using UnityEngine;
using System.Collections;

public class Lever : MonoBehaviour {

	public bool right = false;
	public bool left = false;
	public bool up = true;

	public GameObject[] thingsToMakeActiveLeft;
	public GameObject[] thingsToMakeActiveRight;

	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
		Debug.Log (transform.rotation.z);
		if(Input.GetKeyDown(KeyCode.Y)){
			ActivateLeft();
		}
		if(Input.GetKeyDown(KeyCode.U)){
			ActivateRight();
		}
		/*if(right && !left){
			if(Mathf.Floor(transform.localRotation.eulerAngles.z) != 315){transform.Rotate(0f,0f,45f*Time.deltaTime);}
		}
		if(left && !right){
			if(Mathf.Floor(transform.localRotation.eulerAngles.z) != 45	){transform.Rotate(0f,0f,-45f*Time.deltaTime);}

		}*/
	}

	public void MakeLeverActive(){
		Debug.Log("Lever enabled");
	}

	void OnCollisionEnter(Collision col)
	{
		Debug.Log("COLLISION ENTER " + col.gameObject.name);
		if(col.gameObject.tag == "Player")
		{
			Debug.Log("LEVER ACTIVE");
			ActivateLeft();
		}
		
	}

	public void ActivateLeft(){
		if(up){StartCoroutine(Rotation(transform,new Vector3(0f,0f,45f),1f));}
		if(right){StartCoroutine(Rotation(transform,new Vector3(0f,0f,90f),1f));}
		left = true;
		up = false;
		right = false;
		Debug.Log("Left");

		foreach(GameObject thing in thingsToMakeActiveLeft)
		{
			thing.SetActive(true);
			if(thing.GetComponent<FadeToTrans>() != null){
				thing.GetComponent<FadeToTrans>().discoveryTime = Time.time;
				thing.GetComponent<FadeToTrans>().fadeState = FadeToTrans.FadeState.discovering;
				thing.GetComponent<FadeToTrans>().Reset();
			}
		}
	}
	public void ActivateRight(){
		if(up){StartCoroutine(Rotation(transform,new Vector3(0f,0f,-45f),1f));}
		if(left){StartCoroutine(Rotation(transform,new Vector3(0f,0f,-90f),1f));}
		right = true;
		up=false;
		left=false;
		Debug.Log("Right");

		foreach(GameObject thing in thingsToMakeActiveLeft)
		{
			thing.SetActive(true);
			if(thing.GetComponent<FadeToTrans>() != null){
				thing.GetComponent<FadeToTrans>().discoveryTime = Time.time;
				thing.GetComponent<FadeToTrans>().fadeState = FadeToTrans.FadeState.discovering;
				thing.GetComponent<FadeToTrans>().Reset();
			}
		}
	}

	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;
		}
	}
}
