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

public class PlayerController : MonoBehaviour
{
    public float jumpForce;
    public float delay;
    public LayerMask layerMask;
    private Rigidbody2D rb;
    private BoxCollider2D boxCollider2D;
    private bool isJumping;
    private bool isDoubleJumping;
    private float timestamp;
    void Start()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
        boxCollider2D = gameObject.GetComponent<BoxCollider2D>();
        isJumping = false;
        isDoubleJumping = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (!GameManager.instance.inGame)
        {
            rb.constraints = RigidbodyConstraints2D.FreezeAll;
            return;
        }


        if (isGrounded() && timestamp + delay < Time.time)
        {
            isJumping = false;
            isDoubleJumping = false;
        }


        if (Input.GetMouseButtonDown(0))
        {
            if (!isJumping)
            {
                rb.velocity = new Vector2(0f, jumpForce);
                timestamp = Time.time;
                isJumping = true;
            }
            else if (!isDoubleJumping)
            {
                rb.velocity = new Vector2(0f, jumpForce);
                isDoubleJumping = true;
            }

            
        }
    }

    private bool isGrounded()
    {
        RaycastHit2D hit = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, 0.1f, layerMask);
        return hit.collider != null;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Obstacle"))
        {
            Debug.Log("Przeszkoda!");
            GameManager.instance.GameOver();
        }
    }
}
