using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace HutongGames.PlayMaker.Actions
{
    [ActionCategory("Profiler")]
    public class StopwatchStart : FsmStateAction
    {
        [Tooltip("Id used to look up stopwatch later, e.g., to get elapsed time.")]
        public FsmString id;

        private static readonly Dictionary<string, Stopwatch> Stopwatches = new Dictionary<string, Stopwatch>();
        private static Stopwatch TempStopwatch;

        public override void Reset()
        {
            id = null;
        }

	    public override void OnEnter()
	    {
	        if (!FsmString.IsNullOrEmpty(id))
	        {
	            Stopwatches.Remove(id.Value);

	            var stopwatch = new Stopwatch();
                stopwatch.Start();
	            Stopwatches.Add(id.Value, stopwatch);
	        }
	        else
	        {
                // use temp stopwatch for quick and dirty tests
                // but you will need to add Ids to use multiple stopwatches

	            TempStopwatch = new Stopwatch();
                TempStopwatch.Start();
	        }

	        Finish();
	    }

        public static Stopwatch GetStopwatch(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                if (TempStopwatch != null)
                {
                    return TempStopwatch;
                }

                Debug.LogError("Could not get Stopwatch");
                return null;
            }

            Stopwatch stopwatch;
            if (Stopwatches.TryGetValue(id, out stopwatch))
            {
                return stopwatch;
            }

            Debug.LogError("Could not get Stopwatch: " + id);
            return null;
        }
    }
}
