using System;
using UnityEngine;

namespace UnityStandardAssets._2D
{
    public class PlatformerCharacter2D : MonoBehaviour
    {
        [SerializeField] private float m_MaxSpeed = 10f;                    // The fastest the player can travel in the x axis.
		[SerializeField] private float m_JumpForce = 400f;  				// Amount of force added when the player jumps.
		[SerializeField] private float fuerzaEmpujon = 200; 					// Amount of force added when the player is attaqued.
        [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;  // Amount of maxSpeed applied to crouching movement. 1 = 100%
        [SerializeField] private bool m_AirControl = false;                 // Whether or not a player can steer while jumping;
        [SerializeField] private LayerMask m_WhatIsGround;                  // A mask determining what is ground to the character

        private Transform m_GroundCheck;    // A position marking where to check if the player is grounded.
        const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
        private bool m_Grounded;            // Whether or not the player is grounded.
        private Transform m_CeilingCheck;   // A position marking where to check for ceilings
        const float k_CeilingRadius = .007f; // Radius of the overlap circle to determine if the player can stand up
        private Animator m_Anim;            // Reference to the player's animator component.
        private Rigidbody2D m_Rigidbody2D;
		private SpriteRenderer sprite;
		//private SpriteRenderer
        private bool m_FacingRight = true;  // For determining which way the player is currently facing.
		public int saltos = 0;
		public bool enable;

		public bool tengoDobleSalto = false;
		public bool tengoArma = false;
		private BoxCollider2D cabeza;
		private CircleCollider2D pies;

		public GameObject bala;
		public float[] conteoDeDisparo = {0.5f,0.1f,0.2f,0.1f,0.3f};
		public float velocidadDeDisparo = 1f;
		public float[] conteoDeDisparoReset = {0.5f,0.1f,0.2f,0.1f,0.3f};

		public GameObject armaCortaGallina;
    	public GameObject armaCortaOso;
		public bool golpeando = false;
    	public int tipo = 0;
    	private int ABUELO = 0;
    	private int BABOSA = 1;
    	private int OSO = 2;
   	 	private int GALLINA = 3;

		private bool  herido = false;
		private float tiempoHeridoReset = 1f;
		private float tiempoHerido = 1f;

		SelectorPersonajes persona;

		//private bool colliderMovido = false;

          private void Awake(){
            // Setting up references.
            m_GroundCheck = transform.Find("GroundCheck");
            m_CeilingCheck = transform.Find("CeilingCheck");
            m_Anim = GetComponent<Animator>();
            m_Rigidbody2D = GetComponentInParent<Rigidbody2D>();
			sprite = GetComponentInParent<SpriteRenderer>();
			cabeza = GetComponentInParent<BoxCollider2D>();
			pies = GetComponentInParent<CircleCollider2D>();
			persona = GetComponentInParent<SelectorPersonajes> ();
			if (cabeza.enabled) {
				cabeza.enabled = false;
			}
		}


        private void FixedUpdate(){
			if (enable) {
				m_Grounded = true;

				// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
				// This can be done using layers instead but Sample Assets will not overwrite your project settings.
				/*Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
	            for (int i = 0; i < colliders.Length; i++){
	                if (colliders[i].gameObject != gameObject)
	                    m_Grounded = true;
	            }*/
				//m_Grounded = pies.IsTouchingLayers (m_WhatIsGround) && !(cabeza.IsTouchingLayers (m_WhatIsGround));
				m_Anim.SetBool ("Ground", m_Grounded);

				// Set the vertical animation
				m_Anim.SetFloat ("vSpeed", m_Rigidbody2D.velocity.y);
				m_Anim.SetFloat ("hSpeed", m_Rigidbody2D.velocity.x);

				if (herido) {
					tiempoHerido -= Time.deltaTime;
					if (tiempoHerido <= 0) {
						herido = false;
						tiempoHerido = tiempoHeridoReset;
					}
				}

				if (tipo == BABOSA) {
					if (!persona.colliderMovido) {
						persona.colliderMovido = true;
						pies.offset = new Vector2 (pies.offset.x, pies.offset.y + 0.3f);
					}
				}else{
					if (persona.colliderMovido) {
						persona.colliderMovido = false;
						pies.offset = new Vector2 (pies.offset.x, pies.offset.y - 0.3f);
					}
				}
			}


        }

		public void seleccionar(int sTipo){
			if (tipo == sTipo) {
				m_Anim.enabled = true;
				sprite.enabled = true;
				enable = true;
			} else {
				m_Anim.enabled = false;
				sprite.enabled = false;
				enable = false;
			}
		}

		public void parar(){
			m_Rigidbody2D.velocity = new Vector2 (0,0);
		}

		public void Move(Vector2 move, /*bool crouch, bool jump,*/ bool ataque ){

			// If crouching, check to see if the character can stand up
			//if (!crouch && m_Anim.GetBool ("Crouch")) {
				// If the character has a ceiling preventing them from standing up, keep them crouching
				//if (Physics2D.OverlapCircle (m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround)) {
					//crouch = true;
				//}
			//}

			// Set whether or not the character is crouching in the animator
			//m_Anim.SetBool ("Crouch", crouch);
			/*if (crouch) {
				cabeza.offset = new Vector2 (0.4f, -0.2f);
				cabeza.size = new Vector2 (0.4f, 0.4f);
			} else {
				cabeza.offset = new Vector2 (0f, 0.1f);
				cabeza.size = new Vector2 (0.4f, 0.75f);
			}*/
      if(tipo == ABUELO){
        //if (tengoArma) {
        //  if (!ataqueCorto) {
            m_Anim.SetBool ("ataque", ataque);
            if (ataque) {
              for (int i = 0; i < 1; i++) {
                conteoDeDisparo [i] -= velocidadDeDisparo * Time.deltaTime;
                if (conteoDeDisparo [i] <= 0) {
                  disparar ();
                  conteoDeDisparo [i] = conteoDeDisparoReset [i];
                }
              }
            }
          //}
        //}
      }else if(tipo == GALLINA){
  			if (ataque) {
  				m_Anim.SetTrigger ("ataqueCorto");
  				if (!golpeando) {
  					golpearGallina ();
  				}
  			} else {
  				if (golpeando) {
  					golpeando = false;
  				}
  			}
        m_Anim.SetBool ("ataqueCortoBool",ataque);
      }else if(tipo == OSO){
        if (ataque) {
  				m_Anim.SetTrigger ("ataqueCorto");
  				if (!golpeando) {
  					golpearOso ();
  				}
  			} else {
  				if (golpeando) {
  					golpeando = false;
  				}
  			}
        m_Anim.SetBool ("ataqueCortoBool",ataque);
      }


			/*if(!m_Anim.GetBool ("ataque") ){
				m_Anim.SetBool("atacando", ataque);
				m_Anim.SetTrigger("ataqueCorto");
			}*/



			//only control the player if grounded or airControl is turned on
			if ((m_Grounded || m_AirControl) && !ataque) {
				// Reduce the speed if crouching by the crouchSpeed multiplier
				//move = (crouch ? move * m_CrouchSpeed : move);

				// The Speed animator parameter is set to the absolute value of the horizontal input.
        float vel = Mathf.Abs (move.x)>Mathf.Abs (move.y)?Mathf.Abs (move.x):Mathf.Abs (move.y);
				m_Anim.SetFloat ("Speed", vel);
        		m_Anim.SetFloat ("hSpeed", Mathf.Abs (move.x));
        		m_Anim.SetFloat ("vSpeed", Mathf.Abs (move.y));

				// Move the character
				/*float contraPared = 1;
				if (cabeza.IsTouchingLayers (m_WhatIsGround) && !(pies.IsTouchingLayers (m_WhatIsGround))) {
					if ((m_FacingRight && move.x > 0f) || (!m_FacingRight && move.x < 0f)) {
						contraPared = 0f;
					}
				}*/
				if (!herido) {
					m_Rigidbody2D.velocity = new Vector2 (move.x * m_MaxSpeed, move.y * m_MaxSpeed);
				}

				// If the input is moving the player right and the player is facing left...
				if (move.x > 0 && !m_FacingRight) {
						// ... flip the player.
						Flip ();
					}
	                    // Otherwise if the input is moving the player left and the player is facing right...
	                else if (move.x < 0 && m_FacingRight) {
						// ... flip the player.
						Flip ();
					}
        }
				/*if (!m_Grounded) {
					m_Anim.SetBool ("saltando", true);
				}*/
				/*if (m_Anim.GetBool ("saltando")) {
					m_Rigidbody2D.velocity = new Vector2(m_Rigidbody2D.velocity.x, m_Rigidbody2D.velocity.y-0.1f);
				}*/
				// If the player should jump...
				/*if (tengoDobleSalto) {
					if (saltos < 1) {//m_Grounded && jump && m_Anim.GetBool("Ground"))
						// Add a vertical force to the player.
						if (jump) {
							m_Grounded = false;
							m_Anim.SetBool ("Ground", false);
							if (m_Rigidbody2D.velocity.y > -0.01f) {
								m_Rigidbody2D.AddForce (new Vector2 (0f, m_JumpForce));
							} else {
								m_Rigidbody2D.velocity = new Vector2 (m_Rigidbody2D.velocity.x, 0);
								m_Rigidbody2D.AddForce (new Vector2 (0f, m_JumpForce));
							}
							saltos++;
						}
					}
					if (m_Grounded && m_Anim.GetBool ("Ground")) {
						saltos = 0;
						m_Anim.SetBool ("saltando", false);
					}
				} else {
					if (m_Grounded && jump && m_Anim.GetBool ("Ground")) {
						m_Grounded = false;
						m_Anim.SetBool ("Ground", false);
						m_Rigidbody2D.AddForce (new Vector2 (0f, m_JumpForce));
					}
					if (m_Grounded && m_Anim.GetBool ("Ground")) {
						m_Anim.SetBool ("saltando", false);
					}
				}*/

        }


        private void Flip(){
            // Switch the way the player is labelled as facing.
            m_FacingRight = !m_FacingRight;
            // Multiply the player's x local scale by -1.
            Vector3 theScale = transform.localScale;
            theScale.x *= -1;
            transform.localScale = theScale;
        }

		public void getDobleSalto(){
			tengoDobleSalto = true;
		}

		public void getArma(){
			tengoArma = true;
		}

		void disparar(){
			float desviacion = UnityEngine.Random.Range (-0.5f, 0.5f);
			float rotz = m_FacingRight?(360f+5f*desviacion)*Mathf.Deg2Rad:(180f+5f*desviacion)*Mathf.Deg2Rad;
      Debug.Log("disparo");
			Instantiate (bala,transform.position,Quaternion.Euler(0, 0, rotz));
		}

		void golpearGallina(){
			//float desviacion = UnityEngine.Random.Range (-1.0f, 1.0f);
			float rot = m_FacingRight?0.5f:-0.5f;//(360f)*Mathf.Deg2Rad:(180f)*Mathf.Deg2Rad;
			Vector3 pos = transform.position + new Vector3 ( rot, 0,0);
			Instantiate (armaCortaGallina,pos,transform.rotation);
			golpeando = true;
		}
    	void golpearOso(){
			//float desviacion = UnityEngine.Random.Range (-1.0f, 1.0f);
			float rot = m_FacingRight?0.5f:-0.5f;//(360f)*Mathf.Deg2Rad:(180f)*Mathf.Deg2Rad;
			Vector3 pos = transform.position + new Vector3 ( rot, 0,0);
			Instantiate (armaCortaOso,pos,transform.rotation);
			golpeando = true;
		}

		public void empujon(Vector3 desde){
			Vector3 fuerza = transform.position - desde;
			fuerza.Normalize ();
			m_Rigidbody2D.AddForce(fuerza*fuerzaEmpujon);
			herido = true;
			//Debug.Log ("me pego");
		}

		public bool getEstaEnElPiso(){
			return m_Grounded;
			//Debug.Log ("me pego");
		}
    }
}
