using UnityEngine;

// Do not use this yourself manually, it is set up automatically as required
// Used by the Events class to provide enter_frame and late_update events
namespace com.deeperbeige.lib.runtime
{
	public class EventsComponent : MonoBehaviour
	{
		// Resize tracking
		private int    prevWidth;
		private int    prevHeight;
		private bool   triggerResize;
		private bool   triggerLateResize;
		private bool   triggerPostNGUI;
		
		// Double-back tracking
		private float  backTapped = float.MinValue;
		
		// The current frame number. Updated in LateUpdate, so
		// unless you're reading it from another LateUpdate, it'll
		// be consistent across different scripts. Useful for
		// debugging timing and sync issues.
		//
		// Access with EventsComponent.frame, as long as Events class has been set up
		//
		public static int frame { get; private set; }
		
		public void Init()
		{
			frame             = 0;
			prevWidth         = Screen.width;
			prevHeight        = Screen.height;
			triggerResize     = true;
			triggerLateResize = true;
			triggerPostNGUI   = false;
		}

		private void Update()
		{
			CheckForResize();
			Events.Send(Events.EVENT_UPDATE);
			
			if (Input.GetKeyDown(KeyCode.Menu)) Events.Send(Events.EVENT_UI_SETTINGS);
			if (Input.GetKeyDown(KeyCode.Escape))
		    {
		    	if (backTapped + 0.2f >= Time.time)
		    	{
		    		Events.Send(Events.EVENT_UI_DOUBLE_BACK);
		    		backTapped = float.MinValue;
		    		return;
		    	}
		    	
				Events.Send(Events.EVENT_UI_BACK);
		    	backTapped = Time.time;
			}
		}
		
		public void ForceResizeEvent()
		{
			triggerResize     = true;
			triggerLateResize = true;
		}
		
		private void CheckForResize()
		{
			if (triggerPostNGUI && ! triggerResize)
			{
				Events.Send(Events.EVENT_RESIZE_NEXT_FRAME);
				triggerPostNGUI = false;
			}
			
			if (triggerResize)
			{
				Events.Send(Events.EVENT_RESIZE);
				triggerResize   = false;
				triggerPostNGUI = true;
			}
			
			if (prevWidth == Screen.width && prevHeight == Screen.height) return;
			
			prevWidth  = Screen.width;
			prevHeight = Screen.height;
			
			triggerResize     = true;
			triggerLateResize = true;
		}

		private void FixedUpdate()
		{
			Events.Send(Events.EVENT_FIXED_UPDATE);
		}

		private void LateUpdate()
		{
			Events.Send(Events.EVENT_LATE_UPDATE, (object)frame);
			
			if (triggerLateResize)
			{
				triggerLateResize = false;
				Events.Send(Events.EVENT_RESIZE_LATE);
			}
			
			frame++;
		}
		
		private void OnApplicationFocus(bool focussed)
		{
			Events.Send(focussed ? Events.EVENT_APP_FOCUS : Events.EVENT_APP_DEFOCUS);
		}
		
		private void OnApplicationPause(bool paused)
		{
			Events.Send(paused ? Events.EVENT_APP_PAUSE : Events.EVENT_APP_RESUME);
		}
		
		private void OnApplicationQuit()
		{
			Events.Send(Events.EVENT_APP_QUIT);
		}
		
		private void OnLevelWasLoaded(int levelNumber)
		{
			Events.Send(Events.EVENT_SCENE_CHANGED);
		}
	}
}
