using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;

public class TouchVisualizer : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI startPositionText;
    [SerializeField] private TextMeshProUGUI currentPositionText;
    [SerializeField] private InputActionReference touchActionReference;
    [SerializeField] private GameObject startSprite;
    [SerializeField] private GameObject endSprite;
    [SerializeField] private GameObject lineRendererObject;

    private LineRenderer lineRenderer;
    private InputAction touchAction;
    private bool isTouching;
    private Plane xyPlane;

    void Start()
    {
        // Save the action to a variable so we don't have to keep referring to the '.action' property
        touchAction = touchActionReference.action;
        // We need to make sure the touch action is enabled otherwise the input will not be processed.
        touchAction.Enable();

        xyPlane = new Plane(Vector3.forward, Vector3.zero);
        lineRenderer = lineRendererObject.GetComponent<LineRenderer>();

        // We assume the user is not touching the screen at the start
        OnTouchEnd();
    }

    public void OnTouchStart()
    {
        isTouching = true;
        EnableVisuals();
    }

    public void OnTouchEnd()
    {
        isTouching = false;
        DisableVisuals();
    }

    private void EnableVisuals()
    {
        startSprite.SetActive(true);
        endSprite.SetActive(true);
        lineRendererObject.SetActive(true);
    }

    private void DisableVisuals()
    {
        startPositionText.text = "Touch The Screen";
        currentPositionText.text = "Touch The Screen";
        startSprite.SetActive(false);
        endSprite.SetActive(false);
        lineRendererObject.SetActive(false);
    }

    void Update()
    {
        if (isTouching)
        {
            // Gather touch data from touch action
            TouchState touchState = touchAction.ReadValue<TouchState>();
            Vector2 startPosition = touchState.position;
            Vector2 currentPosition = touchState.startPosition;

            // Set text
            startPositionText.text = $"Start Position: {startPosition}";
            currentPositionText.text = $"Current Position: {currentPosition}";

            // Update positions of sprites and lines
            Vector3 startWorldPosition = TouchUtilities.GetTouchPositionOnPlane(xyPlane, startPosition);
            Vector3 currentWorldPosition = TouchUtilities.GetTouchPositionOnPlane(xyPlane, currentPosition);
            startSprite.transform.position = startWorldPosition;
            endSprite.transform.position = currentWorldPosition;
            lineRenderer.SetPosition(0, startWorldPosition);
            lineRenderer.SetPosition(1, currentWorldPosition);
        }
    }
}
