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

public delegate void OnDragEvent(Vector2 drag);
public delegate void OnDragFinishEvent(Vector2 drag);

public class MouseInputBehaviour : MonoBehaviour
{
    // The main camera
    private new Camera              camera;
    
    // Check if the cursor is currently dragging
    private bool                    isDragging;

    // Get teh initial mouse position when the cursor is first clicked
    private Vector2                 initialCursorPosition;

    // The event handler for on drag
    public event OnDragEvent        onDragHandler;

    // The event handler for on drag finish
    public event OnDragFinishEvent  onDragFinishHandler;

    private void Awake()
    {
        camera = Camera.main;
        isDragging = false;
    }

    private void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (!isDragging)
            {
                isDragging = true;
                Vector3 mousePosition = camera.ScreenToWorldPoint(Input.mousePosition);
                initialCursorPosition = new Vector2(mousePosition.x, mousePosition.y);
            }
            else
            {
                Vector3 mousePosition = camera.ScreenToWorldPoint(Input.mousePosition);
                InvokeDragEvent(new Vector2(mousePosition.x, mousePosition.y) - initialCursorPosition);
            }
        }
        else if (Input.GetMouseButtonUp(0))
        {
            if (isDragging)
            {
                Vector3 mousePosition = camera.ScreenToWorldPoint(Input.mousePosition);
                isDragging = false;
                InvokeDragFinishEvent(new Vector2(mousePosition.x, mousePosition.y) - initialCursorPosition);
            }
        }
    }
    
    private void InvokeDragEvent(Vector2 dragDelta)
    {
        if (onDragHandler != null)
        {
            onDragHandler(dragDelta);
        }
    }

    private void InvokeDragFinishEvent(Vector2 dragDelta)
    {
        if (onDragFinishHandler != null)
        {
            onDragFinishHandler(dragDelta);
        }
    }
}
