using UnityEngine;
using System.Collections;

public class RoomDoorScript : MonoBehaviour {

	public AudioClip partySound1;
	public AudioClip partySound2;
	public AudioClip weWereSleeping;

	private bool haveBeenSilenced = false;

	//public AudioClip shhSound1;
	//public AudioClip shhSound2;

	private float soundRepeatCounter = 0.0f;
	//private float soundRepeatDelay = Random.Range(10.0f, 30.0f);

	public int trainCarNumber = 0;
	private bool isNoisy = false;

	private GameObject noiseIndicator;

	// Use this for initialization
	void Awake () {

		Transform[] childObjects;
		childObjects = gameObject.GetComponentsInChildren<Transform>();
		
		foreach(Transform child in childObjects){
			
			if(child.CompareTag("CabinNoiseIndicator")){
				noiseIndicator = child.gameObject;
			}
			
		}
		
		if(!noiseIndicator){
			Debug.LogError("Can't find door noise indicator!");
		}

	}

	void Start(){

		if(Random.Range(0,2) == 1){
			gameObject.audio.clip = partySound1;
		}else{
			gameObject.audio.clip = partySound2;
		}

		soundRepeatCounter = Random.Range(10.0f, 30.0f);

	}

	// Update is called once per frame
	void Update () {

		soundRepeatCounter -= Time.deltaTime;

		if(isNoisy && soundRepeatCounter <= 0 && !gameObject.audio.isPlaying && !haveBeenSilenced){

			if(Random.Range(0,2) == 1){
				gameObject.audio.clip = partySound1;
			}else{
				gameObject.audio.clip = partySound2;
			}

			gameObject.audio.Play();
			soundRepeatCounter = Random.Range(10.0f, 30.0f);

		}

		//if(Input.GetKeyUp(KeyCode.N)){
		//	makeDoorNoisy();
		//}

	}

	
	public void interactWithDoor(){
		
		// TODO: bang on door, play sound, remove noisy state
		// TODO: if bang on door and they weren't noisy, penalize player
		if(isNoisy){

			//Debug.Log("RoomDoor:: Banged on noisy door.");
			isNoisy = false;
			haveBeenSilenced = true;
			gameObject.audio.Stop();

			noiseIndicator.GetComponent<CabinNoiseIndicatorScript>().disableIndicator();

		}else{

			//Debug.Log("RoomDoor:: Banged on quiet door. Oops.");
			audio.clip = weWereSleeping;
			audio.Play();

		}
		
	}

	public void makeDoorNoisy(){

		isNoisy = true;
		haveBeenSilenced = false;
		noiseIndicator.GetComponent<CabinNoiseIndicatorScript>().enableIndicator();



	}

	public void makeDoorQuiet(){
		isNoisy = false;
		noiseIndicator.GetComponent<CabinNoiseIndicatorScript>().disableIndicator();
	}

	public bool isDoorNoisy(){
		return isNoisy;
	}

	
}
