using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Hero : MonoBehaviour {

	public Dictionary<string,int> keys;
	[SerializeField] private float moveSpeed = 10.0f;

	[SerializeField] private GameObject 	room;
	[SerializeField] private GameObject 	camera;
	private GameObject nearThing;
	private Vector3 cameraDest;

	[SerializeField] string nextScene = "";

	private int interactCooldown = 3;
	private int interactCooldownMax = 3;
	private float lifeLossSpeed = 2.0f;

	private CharacterController charController;
	private Transform myTransform;

	private bool levelComplete = false;

	public AudioClip pickupSound;

	[SerializeField] private int lives;

	void Awake () {
		charController = GetComponent<CharacterController> ();
		myTransform = this.transform;

		SetCameraDest();
	}

	// Use this for initialization
	void Start () {
		keys = new Dictionary<string,int>();
	}

	public void LevelComplete()
	{
		levelComplete = true;
	}

	void OnTriggerEnter(Collider other)
	{
		// Check if you've entered another room.
		if (other.tag == "room")
		{
			// If it's the room we're in, temporarily disable it's collider
			if (other == room)
			{
				other.collider.enabled = false;
			}
			// Otherwise, reinable the room you used to be in's collider, then disable the new ones collider
			else
			{
				room.collider.enabled = true;
				room = other.gameObject;
				room.collider.enabled = false;

				SetCameraDest();
			}
		}
		else if (other.tag == "Robot")
		{
			nearThing = other.gameObject;
		}
	}
	bool robotsAreAttacking()
	{
		Robot[] robots = FindObjectsOfType<Robot>();
		foreach (Robot r in robots)
		{
			if (r.isAttacking()) return true;
		}
		return false;
	}

	void OnTriggerExit(Collider other)
	{
		if (other.tag == "Robot") 
		{
			nearThing = null;
		}
	}

	void OnTriggerStay(Collider other)
	{
		if (other.tag == "Hammer" && lifeLossSpeed<= 0 && robotsAreAttacking()) {
			lives--;
			lifeLossSpeed = 2.0f;
			if (lives <= 0) {
				Application.LoadLevel( Application.loadedLevel);
				Debug.Log("You Died");
			}
		}
	}

	private void SetCameraDest()
	{
		float width = 0f;

		foreach (BoxCollider e in room.GetComponents<BoxCollider> ())
		{
			width += e.size.x;
		}

		cameraDest = new Vector3 (room.transform.position.x,
		                          room.transform.position.y,// + temp/2f,// - 0.5f, 
		                          -width / 2f - 2f);
	}

	private void MoveCamera()
	{
		Vector3 dist = cameraDest - camera.transform.position;
		if (dist.magnitude <= 0.1f) return;

		camera.transform.position += dist * 0.1f;
	}

	private void Move()
	{
		// Actually move the character.
		Vector3 moveVector = Vector3.zero;

		float x = Input.GetAxis ("Horizontal");
		moveVector += (Vector3.right * x);
		float y = Input.GetAxis ("Vertical");
		moveVector += (Vector3.up * y);

		//if (Input.GetKey(KeyCode.UpArrow)) 		{moveVector += Vector3.up; }
		//if (Input.GetKey(KeyCode.DownArrow)) 	{moveVector += Vector3.down;}
		//if (Input.GetKey(KeyCode.RightArrow)) 	{moveVector += Vector3.right;}
		//if (Input.GetKey(KeyCode.LeftArrow)) 	{moveVector += Vector3.left;}
		if (Input.GetKey(KeyCode.Space) || Input.GetButtonDown("Fire1")) 		{interact();}

		if (moveVector == Vector3.zero) {

			animation.CrossFade("anim_idle", 0.4f);

			return;
		}

		animation.CrossFade("anim_walk", 0.2f);
		
		moveVector = moveVector.normalized * moveSpeed;
		charController.Move (moveVector * Time.deltaTime);

		myTransform.position = new Vector3 (myTransform.position.x, myTransform.position.y, -0.5f);

		// Make them face the direction they're going.
		Quaternion rotQuat = Quaternion.LookRotation(moveVector, Vector3.forward);
		myTransform.rotation = Quaternion.RotateTowards(myTransform.rotation, rotQuat, Time.deltaTime * 500.0f);
	}

	// Update is called once per frame
	void Update () {
		lifeLossSpeed -= 1 * Time.deltaTime;
		if (levelComplete)
		{
			myTransform.position += Vector3.back * Time.deltaTime * 2.0f;
			myTransform.eulerAngles -= Vector3.up * Time.deltaTime * 1000.0f;

			if (myTransform.position.z < -10.0f)
			{
				Application.LoadLevel(nextScene);
			}

			return;
		}

		interactCooldown--;
		MoveCamera ();
		Move ();
	}

	public Dictionary<string,int> getKeys()
	{
		return keys;
	}

	public void addkey(string keyName)
	{
		if (keys.ContainsKey(keyName))
			keys[keyName]++;
		else
			keys.Add (keyName,1);

		if(audio != null)
		{
			audio.clip = pickupSound;
			audio.Play ();
		}
	}

    public void removekey(string keyName)
    {
        if (keys.ContainsKey(keyName))
        {
            keys[keyName]--;
        }
        else
        {
            Debug.LogWarning("Using a key you don't have!");
            keys.Add(keyName, -1);
        }
    }

	private void interact()
	{
		if (nearThing != null && interactCooldown <= 0)
		{
			Robot r = (Robot) nearThing.GetComponent<Robot>();
			if (r != null && (string.IsNullOrEmpty(r.RequiredKeys) || hasKey (r.RequiredKeys,r.NoRequiredKeys))) {
				r.interact();
			interactCooldown = interactCooldownMax;
			}
		}
		//for area in front of user, find objects, interact
	}

	public int getLives()
	{
		return lives;
	}

	public bool hasKey(string name)
	{
		if (keys.ContainsKey(name))
		    if (keys[name] > 0)
		    	return true;
		return false;
	}

	public bool hasKey(string name, int no)
	{
		if (keys.ContainsKey(name))
			if (keys[name] >= no)
				return true;
		return false;
	}



}
