using UnityEngine;
using System.Collections;
using UnityEngine.UI;

// Attach this to a UI Text object

[AddComponentMenu( "Utilities/FPS")]
public class FPS : MonoBehaviourSingleton<FPS>
{
    public static int m_fps; // computed fps

    public float m_frequency = 0.5f; // The update frequency of the fps
    public int m_decimal = 1; // How many decimal do you want to display
	
	private float accum   = 0f; // FPS accumulated over the interval
	private int   frames  = 0; // Frames drawn over the interval
	
    private Text m_text;

    protected override void Awake()
    {
        base.Awake();
        m_text = GetComponent<Text>();
    }

    void Start()
	{
        if (m_text)
        {
            StartCoroutine(ProcessFPS());
        }
        else
        {
            Debug.LogError("Attach FPS script to an UI Text object");
        }

        Show(Config.instance.m_data.m_showFps);
    }

    void Update()
	{
        accum += 1.0f / Time.unscaledDeltaTime;
        // accum += Time.timeScale / Time.deltaTime;
        ++frames;
	}

    public static void Show(bool visible)
    {
        instance.m_text.enabled = visible;
        instance.transform.parent.GetComponent<Image>().enabled = visible;
    }

    IEnumerator ProcessFPS()
	{
		while( true )
		{
			// Update the FPS
			float fps = (frames==0) ? 0 : (accum / frames);
            m_fps = Mathf.RoundToInt(fps);
            //m_text.text = fps.ToString( "f" + Mathf.Clamp(m_decimal, 0, 10 ) );
            m_text.text = m_fps.ToString();

            accum = 0.0F;
			frames = 0;
			
			yield return new WaitForSeconds(m_frequency);
		}
	}
}