using System;
using UnityEngine;

namespace ninja
{
    public class NinjaMovement : MonoBehaviour
    {
        [SerializeField] private float m_MaxSpeed = 14f;                   // The fastest the player can travel in the x axis.
		[SerializeField] private float m_JumpForce = 1000f;                // Amount of force added when the player jumps.
		[SerializeField] private float m_WallJumpForce = 1400f;            // Amount of force added when the player jumps of a wall.
		[SerializeField] private float m_WallJumpXForce = 400f;            // Amount of force added when the player jumps of a wall.
        [Range(0, 1)] [SerializeField] private float m_AirSpeed = 1.0f;    // Amount of maxSpeed applied to crouching movement. 1 = 100%
        [SerializeField] private bool m_AirControl = true;                 // Whether or not a player can steer while jumping;
		[SerializeField] private LayerMask m_WhatIsGround = ~0;            // A mask determining what is ground to the character
		[SerializeField] private float m_MaxAirTimeJump = 0.16f*2;
		[SerializeField] private AudioClip[] m_JumpSounds;
		[SerializeField] private AudioClip[] m_LandSounds;

		private Transform m_GroundCheck;    // A position marking where to check if the player is grounded.
		private Transform m_WallCheckLeft;
		private Transform m_WallCheckRight;
		const float k_GroundedRadius = .15f; // Radius of the overlap circle to determine if grounded
		private bool m_Grounded;            // Whether or not the player is grounded.
		private float m_TimeSinceLastGrounded = 0f;
		private bool m_LeftWallTouched;
		private bool m_RightWallTouched;
		private int m_LastWallJump;         // 0=none, 1=left, 2=right
        private Animator m_Anim;            // Reference to the player's animator component.
        private Rigidbody2D m_Rigidbody2D;
        private bool m_FacingRight = true;  // For determining which way the player is currently facing.

        public bool IsFacingRight() { return m_FacingRight; }

        private void Awake()
        {
            // Setting up references.
			m_GroundCheck = transform.Find("GroundCheck");
			m_WallCheckLeft = transform.Find("WallCheckLeft");
			m_WallCheckRight = transform.Find("WallCheckRight");
            m_Anim = GetComponent<Animator>();
            m_Rigidbody2D = GetComponent<Rigidbody2D>();
        }


        private void FixedUpdate()
        {
            m_Grounded = false;

            // 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;
			}

			if (m_Grounded) {
				if (m_TimeSinceLastGrounded > 0.25f) {
					GetComponent<AudioSource> ().PlayOneShot (Util.RandomElement (m_LandSounds), 0.5f);
				}

				m_TimeSinceLastGrounded = 0f;
				m_LastWallJump = 0;
			} else {
				m_TimeSinceLastGrounded += Time.fixedDeltaTime;
			}

			if (m_LastWallJump!=1) {
				colliders = Physics2D.OverlapCircleAll (m_FacingRight ? m_WallCheckLeft.position : m_WallCheckRight.position, k_GroundedRadius, m_WhatIsGround);
				for (int i = 0; i < colliders.Length; i++) {
					if (colliders [i].gameObject != gameObject)
						m_LeftWallTouched = true;
				}
			}
			if (m_LastWallJump != 2) {
				colliders = Physics2D.OverlapCircleAll (m_FacingRight ? m_WallCheckRight.position : m_WallCheckLeft.position, k_GroundedRadius, m_WhatIsGround);
				for (int i = 0; i < colliders.Length; i++) {
					if (colliders [i].gameObject != gameObject)
						m_RightWallTouched = true;
				}
			}

			m_Anim.SetBool("Ground", m_Grounded);

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


        public void Move(float move, bool jump)
        {
            //only control the player if grounded or airControl is turned on
            if (m_Grounded || m_AirControl)
            {
				move = m_Grounded ? move : move * m_AirSpeed;

                // The Speed animator parameter is set to the absolute value of the horizontal input.
                m_Anim.SetFloat("Speed", Mathf.Abs(move));

                // Move the character
				float targetVelocity = move*m_MaxSpeed;
				if (Math.Sign (m_Rigidbody2D.velocity.x) != Math.Sign (targetVelocity) || Math.Abs (m_Rigidbody2D.velocity.x) < Math.Abs (targetVelocity)) {
					float newVelocity = m_Rigidbody2D.velocity.x * 0.8f + targetVelocity * 0.2f;

					m_Rigidbody2D.velocity = new Vector2(newVelocity, m_Rigidbody2D.velocity.y);
				}

                // If the input is moving the player right and the player is facing left...
                if (move > 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 < 0 && m_FacingRight)
                {
                    // ... flip the player.
                    Flip();
                }
            }
            // If the player should jump...
            if (jump) {
				bool jumped = false;

				if (m_Grounded || m_TimeSinceLastGrounded<=m_MaxAirTimeJump) {
					// Add a vertical force to the player.
					m_Anim.SetBool ("Ground", false);
					m_Rigidbody2D.AddForce (new Vector2 (0f, m_JumpForce));
					m_TimeSinceLastGrounded = m_MaxAirTimeJump + 9999f;
					jumped = true;

				} else if (m_LeftWallTouched || m_RightWallTouched) {
					print ("jump "+m_LastWallJump+"  |  "+m_LeftWallTouched+"/"+m_RightWallTouched);
					m_LastWallJump = m_LeftWallTouched ? 1 : 2;

					m_Rigidbody2D.velocity = new Vector2(-m_Rigidbody2D.velocity.x, 0);
					m_Rigidbody2D.AddForce (new Vector2 (m_LeftWallTouched ? m_WallJumpXForce : -m_WallJumpXForce, m_WallJumpForce));
					jumped = true;
				}

				if (jumped && m_JumpSounds.Length>0) {
					GetComponent<AudioSource> ().PlayOneShot(Util.RandomElement (m_JumpSounds), 0.5f);
				}
            }

			m_LeftWallTouched = false;
			m_RightWallTouched = false;
			m_Grounded = 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;
        }
    }
}
