using UnityEngine;
using System.Collections;

public class BatteryScript : MonoBehaviour {
	
	private GameObject player;
	private GameObject playerHand;
	
	public string state = "ground";
	
	public BatteryHolderScript[] batteryHolders;

	// Use this for initialization
	void Start () {
		player = GameObject.Find("Player");
		playerHand = GameObject.Find("Hand_Holdy");
	}
	
	// Update is called once per frame
	void Update () {
		
		
		
		if (state == "ground"){
			
			if (Vector3.Distance(player.transform.position, transform.position)<2.5f){
				
				player.GetComponent<PlayerScript>().message = "It looks like a car battery...\nCould be useful.";
				player.GetComponent<PlayerScript>().messageWipe = Time.time + 0.5f;
				
				if (Input.GetKeyDown("space")){
					if (!player.GetComponent<PlayerScript>().holding){
						state = "held";
						transform.parent = playerHand.transform;
						transform.localPosition = Vector3.zero;
						transform.localEulerAngles = Vector3.zero;
						
						player.GetComponent<PlayerScript>().message = "";
						
						player.GetComponent<PlayerScript>().holding = true;
					}
				}
			}
			
		}else if (state == "held"){
			transform.localPosition = Vector3.zero;
			transform.localEulerAngles = Vector3.zero;
			
			
			for (int i=0; i<batteryHolders.Length; i++){
				if (Vector3.Distance(player.transform.position, batteryHolders[i].transform.position)<2.5f){
					
					if (state != "placed"){
						player.GetComponent<PlayerScript>().message = "Looks like I can put the battery here.";
						player.GetComponent<PlayerScript>().messageWipe = Time.time + 0.5f;
					}
					
					if (Input.GetKeyDown("space") && state != "placed"){
						if (!batteryHolders[i].gotBattery){
							batteryHolders[i].gotBattery = true;
							
							batteryHolders[i].audio.Play();
							
							player.GetComponent<PlayerScript>().message = "";
							
							transform.parent = batteryHolders[i].transform;
							transform.localPosition = Vector3.zero;
							transform.localEulerAngles = Vector3.zero;
							state = "placed";
							
							player.GetComponent<PlayerScript>().holding = false;
							
							continue;
						}
					}
				}
			}
			
		}
		
		
		
	}
}
