using System;
using System.Diagnostics.Tracing;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.U2D;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField]
    private float movePower;
    [SerializeField]
    private float jumpPower;
    [SerializeField]
    [Range(0, 2)]
    private float breakingPower;
    [SerializeField]
    private float maxSpeed;


    public bool isGrounded;
    public bool shallJump;
    public float direction; // float statt Vector2, weil wir nur links/rechts steuern wollen

    private Rigidbody2D rb;
    [SerializeField]
    private ContactFilter2D contactFilter;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        isGrounded = GroundCheck();

        // Springen nur bei Bodenkontakt
        if (isGrounded && shallJump)
        {
            rb.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
            shallJump = false;
            isGrounded = false;
        }
        // Bremsen, wenn Controller auf 0 oder in entgegengesetzte Richtung:
        if ((direction <= 0.05f && direction > -0.05f))
        //|| (rb.linearVelocity.x > 0f && direction < 0f)
        //|| (rb.linearVelocity.x < 0f && direction > 0f))
        {
            if (breakingPower > 1f || breakingPower < 0f)
            {
                rb.linearVelocity = new Vector2(0f, rb.linearVelocityY);
            }
            else
            {
                rb.AddForce(new Vector2(-rb.linearVelocityX, 0f) * breakingPower * movePower, ForceMode2D.Force);
            }

        }
        else
        {
            // Beschleunigen
            rb.AddForce(Vector2.right * direction * movePower, ForceMode2D.Force);

            // bis zu einer gewissen Geschwindigkeit
            if (rb.linearVelocity.magnitude >= maxSpeed)
            {
                rb.linearVelocity = rb.linearVelocity.normalized * maxSpeed;
            }
        }
    }

    private bool GroundCheck()
    {
        return rb.IsTouching(contactFilter);
    }

    // wird von PlayerInput aufgerufen, wenn das auf "SendMessage" steht.
    public void OnMove(InputValue value)
    {
        direction = value.Get<Vector2>().x; // nur rechts-links

        if (direction > 0)
        {
            this.gameObject.transform.localScale = new Vector3(-1f, 1, 1); // sprite schaut entgegengesetzt
        }
        else if(direction < 0)
        {
            this.gameObject.transform.localScale = new Vector3(1f, 1, 1); // sprite schaut in seine normale Richtung
        }
    }
    public void OnJump()
    {
        if (isGrounded)
        {
            shallJump = true;
        }
    }

}
