package ProjectPong;

import MorcoWrapper2D.*;


public class StartManager extends mw2_Script
{
	private int mWinCondition = 5;
	private mw2_Text mWinConditionText;
	private float mRadiusSmall;
	private float mRadiusBig;
	private mw2_Vector2 mOnScreenStart = new mw2_Vector2();
	private mw2_Vector2 mOnScreenPlus = new mw2_Vector2();
	private mw2_Vector2 mOnScreenMinus = new mw2_Vector2();
	private mw2_Audio mPaddleSound;
	private mw2_Audio mMusicSound;
	private mw2_Rect mButtonStart;


	@Override
	public void Start() 
	{
		if (mw2_Globals.HasKey("WinCondition"))
		{
			mWinCondition = mw2_Globals.GetInt("WinCondition");
		}

		mw2_Scene scene = mw2_Application.GetScene();


		mWinConditionText = (mw2_Text) scene.FindObject("winValue");
		mWinConditionText.mText = "" + mWinCondition;

		mw2_Image buttonPlus = (mw2_Image) scene.FindObject("button_plus");
		mw2_Image buttonMinus = (mw2_Image) scene.FindObject("button_minus");
		mButtonStart = (mw2_Rect) scene.FindObject("button_start");

		mOnScreenPlus = scene.mCamera.WorldToScreen( buttonPlus.WorldPosition() );
		mOnScreenMinus = scene.mCamera.WorldToScreen( buttonMinus.WorldPosition() );
		mOnScreenStart = scene.mCamera.WorldToScreen( mButtonStart.WorldPosition() );

		mRadiusSmall = buttonPlus.mSize.x / 2;
		mRadiusBig = mButtonStart.mSize.x / 2;

		mPaddleSound = new mw2_Audio("../__Resources/Pong/sound_paddle.wav");
		mMusicSound = new mw2_Audio("../__Resources/Pong/sound_music.wav");
		mMusicSound.PlayLoop();
	}

	@Override
	public void Update(float deltaTime) 
	{
		// rotate start button
		mButtonStart.RotateWorld(20);

		mw2_Vector2 mouse = mw2_Input.GetMousePos();

		// check mouse click
		if (mw2_Input.GetMouseBtnOnce(mw2_Input.Button.LEFT)) 
		{
			float xPlus = mOnScreenPlus.x - mouse.x;
			float yPlus = mOnScreenPlus.y - mouse.y;

			float xMinus = mOnScreenMinus.x - mouse.x;
			float yMinus = mOnScreenMinus.y - mouse.y;

			float xStart = mOnScreenStart.x - mouse.x;
			float yStart = mOnScreenStart.y - mouse.y;

			if (xPlus * xPlus + yPlus * yPlus <= mRadiusSmall * mRadiusSmall) 
			{
				if (mWinCondition < 99) 
				{
					mWinCondition += 1;
					mWinConditionText.mText = "" + mWinCondition;
				}
				mPaddleSound.PlayOnce();
			} 
			else if (xMinus * xMinus + yMinus * yMinus <= mRadiusSmall * mRadiusSmall) 
			{
				if (mWinCondition > 1) 
				{
					mWinCondition -= 1;
					mWinConditionText.mText = "" + mWinCondition;
				}
				mPaddleSound.PlayOnce();
			} 
			else if (xStart * xStart + yStart * yStart <= mRadiusBig * mRadiusBig) 
			{
				mw2_Globals.SetInt("WinCondition", mWinCondition);
				mw2_Application.LoadScene( new GameScene(), new GameManager() );
			}
		}

		if (mw2_Input.GetKeyOnce(mw2_Input.Key.ESC)) 
		{
			mw2_Application.Exit();
		}
	}

	@Override
	public void Stop() 
	{
		mMusicSound.Stop();
	}
}

		
