using UnityEngine;
using System.Collections;

[RequireComponent (typeof(Rigidbody2D))]
public class Movement : MonoBehaviour {

	Animator animator;
	Rigidbody2D rigidbody2d;
	public float velocidadNormal = 4f;
	public float velocidadCorriendo = 6f;
	private float horizontal, vertical;
	private bool delay;

	private int direccion = 1; // 1 arriba, 2 derecha, 3 abajo, 4 arriba

	public GameObject[] spells;


	void Start () {
		//Debug.Log (MapGenerator.mapGen.rooms [0, 0]);
		if(MapGenerator.mapGen != null){
			Vector3 posicionInicial = new Vector3 (MapGenerator.mapGen.rooms[0,0] + 2, MapGenerator.mapGen.rooms[1,0] + 2, -0.3f);
			transform.position = posicionInicial;
		}
		animator = GetComponent<Animator> ();
		if(animator == null){
			animator = gameObject.AddComponent<Animator>();
		}
		rigidbody2d = GetComponent<Rigidbody2D> ();
	}

	void FixedUpdate(){

		Vector2 _movimiento = new Vector2 (horizontal, vertical);
		Vector2 _normalized = _movimiento.normalized;
		
		if (Input.GetKey (KeyCode.LeftShift)) {
			horizontal = _normalized.x * velocidadCorriendo * Time.deltaTime;
			vertical = _normalized.y * velocidadCorriendo * Time.deltaTime;
		}else{
			horizontal = _normalized.x * velocidadNormal * Time.deltaTime;
			vertical = _normalized.y * velocidadNormal * Time.deltaTime;
		}

		/*_horizontal = (horizontal > 0) ? _horizontal : -_horizontal;
		_vertical = (vertical > 0) ? _vertical : -_vertical;*/

		rigidbody2d.MovePosition(new Vector2(transform.position.x + horizontal, transform.position.y + vertical));
	}

	void Update () {
		horizontal = Input.GetAxis("Horizontal");
		vertical = Input.GetAxis("Vertical");

		if(Input.GetMouseButtonDown(0)){
			if(!delay){
				//Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition));
				GameObject _spell = (GameObject) Instantiate (spells[EstadoPartida.estadoPartida.seleccion], transform.position, Quaternion.identity);
				Spells _stats = _spell.GetComponent<Spells>();
				_stats.FijarDireccion(new Vector2 (- transform.position.x + Camera.main.ScreenToWorldPoint(Input.mousePosition).x, - transform.position.y + Camera.main.ScreenToWorldPoint(Input.mousePosition).y), BANDO.Aliado, this.transform);
				delay = true;
				StartCoroutine(Findelay(_stats.delay));
			}
		}

		if(Input.GetKeyDown("1")){
			EstadoPartida.estadoPartida.seleccion = 0;
		} else if(Input.GetKeyDown("2")){
			EstadoPartida.estadoPartida.seleccion = 1;
		}

		if (vertical > 0 && vertical > horizontal) {
			direccion = 1;
		} else if (horizontal > 0 && vertical < horizontal) {
			direccion = 2;
		} else if (vertical < 0 && vertical < horizontal) {
			direccion = 3;
		} else if (horizontal < 0 && vertical > horizontal) {
			direccion = 4;
		}

		if(horizontal == 0 && vertical == 0){
			animator.SetBool ("quieto", true);
		}else{
			animator.SetBool ("quieto", false);
		}
		animator.SetInteger("direccion", direccion);
	}

	IEnumerator Findelay (float tiempo){
		yield return new WaitForSeconds (tiempo);
		delay = false;
	}
}
