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

public class playerMovement : MonoBehaviour
{
    public float jumpForce = 200f;
    public float moveSpeed = 5.0f;

    private Rigidbody2D _rigidbody2D;
    private float horizontalMovement;
    private float verticalMovement;

    private PlayerInteract pInteract;

    private bool grounded;
    private bool isJumping;

    public Vector3 playerPos;

    Animator animator;

    void Awake()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        pInteract = GetComponent<PlayerInteract>();
        animator = GetComponent<Animator>();
        grounded = true;
        animator.SetBool("isWalking", false);
        animator.SetBool("isJumping", false);
    }

    void FixedUpdate()
    {
        if(!pInteract.isGameOverW && !pInteract.isGameOverL)
        {
            horizontalMovement = Input.GetAxis("Horizontal") * moveSpeed;
            verticalMovement = Input.GetAxis("Vertical") * moveSpeed;

            _rigidbody2D.velocity = new Vector2(horizontalMovement, _rigidbody2D.velocity.y);

            if (horizontalMovement != 0 || (verticalMovement != 0 && pInteract.collisionObject.gameObject.tag == "Ladder"))
            {
                animator.SetBool("isWalking", true);
            }
            else
            {
                animator.SetBool("isWalking", false);
            }

            if (isJumping)
            {
                animator.SetBool("isJumping", true);
            }
            else
            {
                animator.SetBool("isJumping", false);
            }

            if (horizontalMovement < 0)
            {
                transform.localRotation = Quaternion.Euler(0, 180, 0);
            }
            else if (horizontalMovement > 0)
            {
                transform.localRotation = Quaternion.Euler(0, 0, 0);
            }

        }
    }

    private void Update()
    {
        playerPos = new Vector3(transform.position.x, transform.position.y, transform.position.z) ;

        if (pInteract.canClimb)
        {
            _rigidbody2D.velocity = new Vector2(_rigidbody2D.velocity.x, verticalMovement);
            if (Input.GetKeyDown(KeyCode.S) || Input.GetKey(KeyCode.W))
            {
                pInteract.ladderChildActive(false);
            }
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (grounded)
            {
                _rigidbody2D.AddForce(new Vector2(0, jumpForce));
                grounded = false;
            }
            isJumping = true;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Platform" || collision.gameObject.tag == "Ladder")
        {
            grounded = true;
            isJumping = false;
        }
    }
}
