using UnityEngine;
using System.IO;
using System.Text;
using System;

public class PositionTracker : MonoBehaviour
{
    [Header("Objects to Track")]
    [Tooltip("First object to track position")]
    public Transform object1;
    
    [Tooltip("Second object to track position")]
    public Transform object2;

    [Header("Tracking Settings")]
    [Tooltip("How often to record positions (in seconds)")]
    public float recordInterval = 0.1f;
    
    [Tooltip("Custom filename (without extension). Leave empty for auto-generated name")]
    public string customFileName = "";
    
    [Tooltip("Start tracking automatically on scene load")]
    public bool autoStart = true;

    private string filePath;
    private float timer;
    private bool isTracking;
    private StreamWriter writer;
    private int frameCount;

    private void Start()
    {
        if (autoStart)
        {
            StartTracking();
        }
    }

    public void StartTracking()
    {
        if (object1 == null || object2 == null)
        {
            Debug.LogError("PositionTracker: Both objects must be assigned in the inspector!");
            return;
        }

        // Generate filename with timestamp
        string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
        string fileName = string.IsNullOrEmpty(customFileName) 
            ? $"PositionData_{timestamp}.csv" 
            : $"{customFileName}_{timestamp}.csv";
        
        filePath = Path.Combine(Application.persistentDataPath, fileName);

        try
        {
            // Create and open the file
            writer = new StreamWriter(filePath, false, Encoding.UTF8);
            
            // Write CSV header
            writer.WriteLine("Timestamp,Frame,Object1_Name,Object1_X,Object1_Y,Object1_Z,Object2_Name,Object2_X,Object2_Y,Object2_Z");
            
            isTracking = true;
            frameCount = 0;
            timer = 0f;
            
            Debug.Log($"PositionTracker: Started tracking. Data will be saved to: {filePath}");
        }
        catch (Exception e)
        {
            Debug.LogError($"PositionTracker: Failed to create CSV file. Error: {e.Message}");
        }
    }

    public void StopTracking()
    {
        if (isTracking && writer != null)
        {
            writer.Close();
            isTracking = false;
            Debug.Log($"PositionTracker: Stopped tracking. Data saved to: {filePath}");
        }
    }

    private void Update()
    {
        if (!isTracking || writer == null)
            return;

        timer += Time.deltaTime;

        if (timer >= recordInterval)
        {
            RecordPositions();
            timer = 0f;
        }

        // Press 'T' to toggle tracking, 'S' to stop and save
        if (Input.GetKeyDown(KeyCode.T))
        {
            if (isTracking)
                StopTracking();
            else
                StartTracking();
        }
    }

    private void RecordPositions()
    {
        if (object1 == null || object2 == null)
            return;

        frameCount++;
        
        Vector3 pos1 = object1.position;
        Vector3 pos2 = object2.position;
        
        string timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
        
        // Write data row
        string dataRow = $"{timestamp},{frameCount}," +
                        $"{object1.name},{pos1.x:F4},{pos1.y:F4},{pos1.z:F4}," +
                        $"{object2.name},{pos2.x:F4},{pos2.y:F4},{pos2.z:F4}";
        
        writer.WriteLine(dataRow);
        writer.Flush(); // Ensure data is written immediately
    }

    private void OnDestroy()
    {
        StopTracking();
    }

    private void OnApplicationQuit()
    {
        StopTracking();
    }

    // Helper method to open the folder containing the CSV file
    [ContextMenu("Open Data Folder")]
    public void OpenDataFolder()
    {
        Application.OpenURL(Application.persistentDataPath);
    }
}

