using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;

public class Food_MB : MonoBehaviour
{
    public bool isTouchingMouse = false;
    public bool isheld = false;

    public float defaultFoodSpeed = 1f;
    public float gravity = 1f;
    private float foodSpeed = 1f;
    private float noGravity = 0f;

    private PlayerInput playerInput;

    private InputAction hold;

    private Vector2 mousePos;

    private Rigidbody2D foodRb;

    void Start()
    {
        playerInput = GetComponent<PlayerInput>();
        if (playerInput != null)
        {
            hold = playerInput.currentActionMap.FindAction("Hold");
        }
        foodSpeed = defaultFoodSpeed;
        foodRb = GetComponent<Rigidbody2D>();
        foodRb.gravityScale = gravity;
    }

    private void Update()
    {
        // 获取鼠标位置

        mousePos = Mouse.current.position.ReadValue();

        // 将屏幕位置转换为世界位置

        Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0));

        // 检查鼠标是否触摸到此 GameObject 的碰撞器,并且是否正在执行 Hold 动作

        Collider2D hit = Physics2D.OverlapPoint(worldPos);

        if (hit != null && hit.gameObject == this.gameObject && hold != null && hold.IsPressed())
        {
            //Debug.Log("Hold action is being performed");
            foodRb.gravityScale = noGravity;
            isheld = true;
            foodSpeed = defaultFoodSpeed;
            transform.position = Vector2.MoveTowards(transform.position, worldPos, foodSpeed * Time.deltaTime);
        }
        else if (hold.IsPressed() && (hit == null || !hit.gameObject == this.gameObject) && isheld == true)
        {
            //Debug.Log("Mouse is not touching the object but object is held");
            foodSpeed = foodSpeed + 1f;
            transform.position = Vector2.MoveTowards(transform.position, worldPos, foodSpeed * Time.deltaTime);
        }
        if (!hold.IsPressed())
        {
            //Debug.Log("Object dropped!");
            foodRb.gravityScale = gravity;
            foodSpeed = defaultFoodSpeed;
            isheld = false;
        }
        // 如果 Hold 动作释放后立即应用速度
        if (!hold.IsPressed() && isheld == true)
        {
            transform.position = Vector2.MoveTowards(transform.position, worldPos, foodSpeed * Time.deltaTime);
        }
    }
}