﻿using UnityEngine;

public class FramerateManager : MonoBehaviour
{
	public bool vsyncEnabled = false;
	public KeyCode toggleVsyncKey = KeyCode.V;

	public bool showFramerate = true;
	public KeyCode toggleFPSKey = KeyCode.F;
	public float showAtScreenPercentageFromLeft = 0.9f;
	public float showAtScreenPercentageFromTop = 0.05f;
	
	private float counter;
	private int frames;
	private float fps;
	private GUIStyle whiteStyle;
	private GUIStyle blackStyle;
	
	public void Start()
	{
		GUIStyleState whiteStyleState = new GUIStyleState();
		whiteStyleState.textColor = Color.white;
		
		whiteStyle = new GUIStyle();
		whiteStyle.fontSize  = 20;
		whiteStyle.fontStyle = FontStyle.Bold;
		whiteStyle.alignment = TextAnchor.UpperCenter;
		whiteStyle.normal    = whiteStyleState;
		
		blackStyle = new GUIStyle(whiteStyle);
		blackStyle.normal.textColor = Color.black;
	}
	
	public void OnGUI()
	{
		if(showFramerate)
		{
			var sw   = (float)Screen.width;
			var sh   = (float)Screen.height;
			var rect = new Rect(sw * showAtScreenPercentageFromLeft, sh * showAtScreenPercentageFromTop - 10f, 0f, 30.0f);
			var text = fps.ToString("0.0") + " FPS";
			
			rect.x += 1;
			GUI.Label(rect, text, blackStyle);
			
			rect.x -= 2;
			GUI.Label(rect, text, blackStyle);
			
			rect.x += 1;
			rect.y += 1;
			GUI.Label(rect, text, blackStyle);
			
			rect.y -= 2;
			GUI.Label(rect, text, blackStyle);
			
			rect.y += 1;
			GUI.Label(rect, text, whiteStyle);
		}
	}
	
	public void LateUpdate()
	{
		if(toggleFPSKey != KeyCode.None && Input.GetKeyDown(toggleFPSKey))
			showFramerate = !showFramerate;
		
		if(toggleVsyncKey != KeyCode.None && Input.GetKeyDown(toggleVsyncKey))
			vsyncEnabled = !vsyncEnabled;

		if(vsyncEnabled == true && QualitySettings.vSyncCount == 0)
			QualitySettings.vSyncCount = 1;
		else if(vsyncEnabled == false && QualitySettings.vSyncCount > 0)
			QualitySettings.vSyncCount = 0;
		
		counter += Time.deltaTime;
		frames  += 1;
		
		if (counter >= 1.0f)
		{
			fps = (float)frames / counter;
			
			counter = 0.0f;
			frames  = 0;
		}
	}
}
