using UnityEngine;
using System.Collections;

public class LeverController : MonoBehaviour {

	public int status; //0=false, 1= true
	private float curstatus; //
	public GameObject lever;
	public GameObject[] affectedObjs;
	private Vector3[] initPos;
	public Vector3[] offset;
	public float duration;

	private float curDuration;

	// Use this for initialization
	void Start () {
		curstatus = status;
		curDuration = 0;
		initPos = new Vector3[affectedObjs.Length];
		for(int i=0; i<affectedObjs.Length; ++i) initPos[i] = affectedObjs[i].transform.localPosition;
	}

	void Update(){
		if (Input.GetKeyDown(KeyCode.LeftShift) ||Input.GetKeyDown(KeyCode.RightShift) ){
			GameObject[] lis = GameObject.FindGameObjectsWithTag("Player");
			foreach(GameObject g in lis){
				if (this.GetComponent<Collider2D>().IsTouching(g.GetComponent<Collider2D>())){
					TriggerLever();
					return;
				}
			}
		}
	}

	
	// Update is called once per frame
	void FixedUpdate () {
		if (curDuration>0){
			curDuration-=Time.fixedDeltaTime;
			if (curDuration<0) curDuration = 0;

			for(int i=0; i<affectedObjs.Length; ++i) {
				float a,b;
				a = (curDuration/duration);
				b = (1 - 2*(curDuration/duration));
				affectedObjs[i].transform.localPosition = (initPos[i] + offset[i] * (a + b*(status)));
			}
		}
		float nexstatus = (curstatus*4 + status)/5;
		lever.transform.RotateAround(this.transform.position, Vector3.forward, (curstatus - nexstatus) * 90f);
		curstatus = nexstatus;
	}
 
	/*
	void OnTriggerEnter2D(Collider2D other){  
		if (other.gameObject.tag == "Player"){
			TriggerLever();

		}
	}*/

	public void TriggerLever(){
		
		//trigger lever
		status = 1 - status; 
		if (curDuration ==0) curDuration = duration;
		else curDuration = duration - curDuration;
	}
}
