using UnityEngine;
using System.Collections;

public class TrainCarWindowScript : MonoBehaviour {

	public int trainCarNumber = 0;
	private float animationSpeed = 0.5f;
	private bool isWindowOpen = false;

	private GameObject curtains;
	private bool haveStoppedCurtainWiggle = false;
	
	// Use this for initialization
	void Awake () {

		Transform[] childObjects;
		childObjects = gameObject.GetComponentsInChildren<Transform>();

		foreach(Transform child in childObjects){

			if(child.CompareTag("Curtains")){
				curtains = child.gameObject;
			}

		}

		if(!curtains){
				Debug.LogError("Can't find my curtains!");
		}

	}
	
	// Update is called once per frame
	void Update () {
		
		//if(Input.GetKeyUp(KeyCode.Space)){
		//	interactWithDoor();
		//}

		// Only stop wiggling curtains once window is totally closed
		if(!gameObject.animation.isPlaying && !isWindowOpen && !haveStoppedCurtainWiggle){
			curtains.GetComponent<TrainCarWindowCurtainScript>().stopWiggle();
			haveStoppedCurtainWiggle = true;

			gameObject.audio.Stop();

		}
		
	}
	
	public void openWindow(){
		
		gameObject.animation["OpenWindow"].speed = animationSpeed;
		gameObject.animation.Play();

		isWindowOpen = true;

		curtains.GetComponent<TrainCarWindowCurtainScript>().startWiggle();
		haveStoppedCurtainWiggle = false;

		gameObject.audio.Play();

	}
	
	public void closeWindow(){
		
		gameObject.animation["OpenWindow"].speed = -animationSpeed;
		gameObject.animation["OpenWindow"].time = gameObject.animation["OpenWindow"].length;
		gameObject.animation.Play();

		isWindowOpen = false;

	}
	
	public void interactWithWindow(){
		
		if(!isWindowOpen){
			
			openWindow();
			//isWindowOpen = true;

			//curtains.GetComponent<TrainCarWindowCurtainScript>().startWiggle();
			//haveStoppedCurtainWiggle = false;
			
		}else{
			
			closeWindow();
			//isWindowOpen = false;
			
		}
		
	}

	public bool isWindowDown(){
		return isWindowOpen;
	}
	
}
