using UnityEngine;
using System.Collections;

public class GeneratorScript : MonoBehaviour {

	public bool on = false;
	
	public Light generatorLight;
	
	public Transform playerLoc;
	public Transform camLoc;
	private GameObject animObj;
	
	private GameObject player;
	
	private float flickerTime = 0f;
	
	private bool startingUp = false;
	
	private float finishStarting = 0f;
	
	public AudioSource genAudio;
	
	// Use this for initialization
	void Start () {
		player = GameObject.Find("Player");
		flickerTime = Random.Range(0f,10f);
		animObj = GameObject.Find("CharaModel03");
	}
	
	// Update is called once per frame
	void Update () {
		if (!startingUp){
			
			if (!on){
				
				if (Vector3.Distance(player.transform.position, transform.position)<2.5f){
					
					player.GetComponent<PlayerScript>().message = "Looks like I can use this...";
					player.GetComponent<PlayerScript>().messageWipe = Time.time + 0.5f;
					
					if (Input.GetKeyDown("space")){
						startingUp = true;
						player.transform.position = playerLoc.position;
						animObj.transform.LookAt(animObj.transform.position + playerLoc.forward);
						animObj.animation.Play("startGenerator");
						GameObject.Find("Main Camera").transform.position = camLoc.position;
						GameObject.Find("Main Camera").transform.rotation = camLoc.rotation;
						player.GetComponent<PlayerScript>().startingEngine = true;
						
						player.GetComponent<PlayerScript>().message = "";
					}
				}
				
			}
			
		}else{
			
			if (!on){
				if (animObj.animation["startGenerator"].normalizedTime > 0.63f){
					on = true;
					genAudio.Play();
					finishStarting = Time.time + 1.5f;
				}
			}else{
				if (Time.time > finishStarting){
					startingUp = false;
					player.GetComponent<PlayerScript>().startingEngine = false;
				}
			}
			
		}
		
		if (!on){
			generatorLight.color = Color.red;
			if (flickerTime<Time.time){
				flickerTime = Time.time + 0.5f;
				generatorLight.enabled = !generatorLight.enabled;
			}
		}else{
			generatorLight.color = Color.green;
			generatorLight.enabled = true;
		}
		
		
		
	}
}
