using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

public class PlayerController : MonoBehaviour
{
    public Vector2 respawnLocation;

    [SerializeField] float jumpHeight = 1f;
    [SerializeField] float speed = 1f;
    [SerializeField] float decelerationRate;

    private Rigidbody2D rb;
    private float movementX;
    private float maxHorizontalSpeed = 4f;
    private bool jump_pressed = false;
    private bool doubleJumped = false;
    private bool grounded = false;
    private int groundLayer;
    private Vector2 startingPoint;
    SwapManager swapManager;


    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        groundLayer = LayerMask.GetMask("Platform");
        respawnLocation = transform.position;
        startingPoint = transform.position;
        swapManager = GameObject.Find("PlatformManager").GetComponent<SwapManager>();
    }

    public void OnJump()
    {
        jump_pressed = true;
    }

    void OnMove(InputValue movementValue)
    {
        
        movementX = movementValue.Get<Vector2>().x;
    }

    void FixedUpdate()
    {
        if (movementX == 0)
        {
            rb.velocity += new Vector2(rb.velocity.x * decelerationRate, 0);
        } else
        {
            Vector2 movement = new Vector2(movementX, 0.0f);
            rb.AddForce(movement * speed);
            if (Mathf.Abs(rb.velocity.x) > maxHorizontalSpeed)
            {
                rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x)*maxHorizontalSpeed, rb.velocity.y);
            }
        }

        grounded = false;
        Vector2 playerBottom = transform.position;
        playerBottom.y -= GetComponent<BoxCollider2D>().bounds.extents.y;
        if (Physics2D.Raycast(playerBottom, Vector2.down, 0.1f, groundLayer))
        {
            grounded = true;
            doubleJumped = false;
        }
        if (jump_pressed)
        {
            if (grounded)
            {
                rb.AddForce(Vector2.up * jumpHeight);
            } else if (!doubleJumped)
            {
                doubleJumped = true;
                rb.velocity = new Vector2(rb.velocity.x, 0f);
                rb.AddForce(Vector2.up * jumpHeight);
                swapManager.Swap();
            }
            Debug.Log(Physics2D.Raycast(playerBottom, Vector2.down, 0.1f).collider.name);
            Debug.DrawLine(playerBottom, playerBottom + Vector2.down * 0.1f);
            
        }
        jump_pressed = false;

    }

}
