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

public class PlayerMove : MonoBehaviour
{
    [SerializeField]
    private float Speed = 200;
    [SerializeField]
    private float JumpForce = 20;
    private Rigidbody2D rigid = null;
    void Start()
    {
        if (this.TryGetComponent(out Rigidbody2D rg)) this.rigid = rg;
        if (this.TryGetComponent(out Animator an)) an.SetInteger("State", 1);
        if (this.TryGetComponent(out Transformacion trans)) trans.HumanToSlime();
    }

    // Update is called once per frame
    void Update()
    {
        if(rigid != null)
        {
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetKeyDown(KeyCode.Space) ? 1 : 0;
            float running = Input.GetKey(KeyCode.LeftShift) ? 2 : 1;

            if ( h != 0 ) this.rigid.velocity = new Vector2(h * Time.deltaTime * Speed * running * isColliding(h), this.rigid.velocity.y);
            if (v > 0f) Jump();

            if(this.TryGetComponent(out Animator an))
            {
                an.SetBool("Walking", (this.rigid.velocity.x != 0) );
                an.SetBool("Jumping", isJumping());
            }
            if(this.TryGetComponent(out SpriteRenderer sr))
            {
                if(rigid.velocity.x != 0) sr.flipX = (rigid.velocity.x < 0);
            }
        }
    }


    #region FUNCIONES DE MOVIMIENTO

    private void Jump()
    {
        GameObject feet = this.transform.Find("Feet").gameObject;
        if (feet != null)
        {
            if (feet.TryGetComponent(out Touching feetTouch))
            {
                if(feetTouch.touching)
                {
                    this.rigid.AddForce( Vector2.up * this.JumpForce, ForceMode2D.Impulse);
                }
            }
        }
    }
    private bool isJumping()
    {
        GameObject feet = this.transform.Find("Feet").gameObject;
        if (feet != null)
        {
            if (feet.TryGetComponent(out Touching feetTouch))
            {
                return !feetTouch.touching;
            }
        }
        return false;
    }
    private int isColliding(float Direction)
    {
        GameObject[] childs = new GameObject[] { this.transform.Find("LeftSide").gameObject, this.transform.Find("RightSide").gameObject };

        Touching leftBox = null;
        Touching rightBox = null;

        if (childs[0].TryGetComponent(out Touching lBox)) leftBox = lBox;
        if (childs[1].TryGetComponent(out Touching rBox)) rightBox = rBox;

        int result = 1;

        if (leftBox != null && leftBox.touching && Direction < 0 ) result = 0;
        if (rightBox != null && rightBox.touching && Direction > 0 ) result = 0;

        return result;
    }
    #endregion FIN FUNCIONES DE MOVIMIENTO
}
