using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ShootingHero.Scene;
using ShootingHero.Components;
using ShootingHero.Components.Backgrounds;
using Microsoft.Xna.Framework.Input;

namespace ShootingHero
{
	public class Transitor : DrawableGameComponent
	{
		Texture2D fadeTexture;
		float alphaValue = 0;
		bool fadeIn = false, fadeOut = false;

		DrawableGameComponent currentScene, nextScene;

		public DrawableGameComponent CurrentScene { get { return currentScene; } }

		public Texture2D FadeTexture { get { return fadeTexture; } }

		public void Transition ( DrawableGameComponent scene )
		{
			nextScene = scene;
			fadeOut = true;
			alphaValue = 0;
		}

		public Transitor ( Game game )
			: base ( game )
		{
			alphaValue = 1;
			fadeIn = true;
			currentScene = new LogoScene ( Game );
			currentScene.Initialize ();
		}

		protected override void LoadContent ()
		{
			fadeTexture = new Texture2D ( GraphicsDevice, 1, 1 );
			fadeTexture.SetData<Color> ( new Color [] { Color.Black } );

			base.LoadContent ();
		}

		public override void Update ( GameTime gameTime )
		{
			if ( !fadeIn && !fadeOut )
			{
				if ( currentScene != null )
					currentScene.Update ( gameTime );
			}
			else if ( fadeOut )
			{
				GamePad.SetVibration ( PlayerIndex.One, 0, 0 );
				alphaValue += gameTime.ElapsedGameTime.Milliseconds / 500.0f;
				if ( alphaValue >= 1.0f )
				{
					alphaValue = 1.0f;
					currentScene.Dispose ();
					currentScene = nextScene;
					currentScene.Initialize ();
					Game.ResetElapsedTime ();
					fadeIn = true;
					fadeOut = false;
				}
			}
			else if ( fadeIn )
			{
				alphaValue -= gameTime.ElapsedGameTime.Milliseconds / 500.0f;
				if ( alphaValue <= 0.0f )
				{
					alphaValue = 0.0f;
					fadeIn = false;
					fadeOut = false;
				}
			}

			base.Update ( gameTime );
		}

		public override void Draw ( GameTime gameTime )
		{
			SpriteBatch spriteBatch = ( Game as ShootingHero ).SpriteBatch;
			spriteBatch.Begin (SpriteSortMode.Deferred, BlendState.NonPremultiplied);

			if ( currentScene != null )
				currentScene.Draw ( gameTime );

			spriteBatch.Draw ( fadeTexture, new Rectangle ( 0, 0, 480, 800 ), new Color ( 1, 1, 1, alphaValue ) );

			spriteBatch.End ();

			base.Draw ( gameTime );
		}

		protected override void UnloadContent ()
		{
			fadeTexture.Dispose ();
			fadeTexture = null;

			base.UnloadContent ();
		}
	}
}
