using UnityEngine;
using System.Collections;

public class BulletTime : MonoBehaviour
{
	public float BulletTimeScale		= 0.5f;
	public float BulletTimeDuration		= 2.5f;
	public float BulletTimeEnterExitDur = 0.5f;
	private bool m_active				= false;
	private bool m_entering				= false;
	private bool m_quiting				= false;
	private float m_curDur				= 0.0f;

	float LinearInterpolation( float t, float b, float c, float d )
	{
		return b + t * c / d;
	}

	void Start ()
	{
	
	}
	
	void Update ()
	{
		if ( m_active )
		{
			if ( m_entering )
			{
				m_curDur += Time.fixedDeltaTime;
				
				Time.timeScale = 1 - LinearInterpolation( m_curDur, 0, BulletTimeScale, BulletTimeDuration );
				
				if ( m_curDur >= BulletTimeEnterExitDur )
				{
					Time.timeScale	= BulletTimeScale;
					m_entering		= false;
					m_curDur		= 0;
				}
			}
			else if ( m_quiting )
			{

				m_curDur += Time.fixedDeltaTime;

				Time.timeScale = 1 - BulletTimeScale + LinearInterpolation( m_curDur, 0, BulletTimeScale, BulletTimeDuration );

				if ( m_curDur >= BulletTimeEnterExitDur )
				{
					m_quiting = false;
					Deactivate();
				}
			}
			else
			{
				m_curDur += Time.fixedDeltaTime;

				if ( m_curDur >= BulletTimeDuration )
				{
					m_curDur = 0;
					m_quiting = true;
				}
			}
		}
		else
		{
			if ( Input.GetKeyDown( KeyCode.X ) )
			{
				Activate();
			}
		}
	}

	void Deactivate()
	{
		if ( m_active )
		{
			m_active = false;
			m_curDur = 0;
			Time.timeScale = 1;
		}
	}

	void Activate()
	{
		if ( !m_active )
		{
			m_entering = true;
			m_active = true;
		}
	}
}
