using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using MegaManRipoff.MainGameClasses;
using MegaManRipoff.TitleScreenClasses;
using MegaManRipoff.GameOverClasses;
using MegaManRipoff.YouWinClasses;

namespace MegaManRipoff
{
    /// <summary>
    /// This is the main type for my game!!
    /// </summary>
    public class Game1 : Game
    {
        #region Member Variables

        //XNA required initialisations.
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        /// <summary>
        /// All possible states of the game.
        /// </summary>
        public enum State
        {
            None, TitleScreen, MainGame, GameOverScreen, YouWinScreen
        }

        /// <summary>
        /// The current state of the game.
        /// </summary>
        State _currentState;

        /// <summary>
        /// The title screen instance.
        /// </summary>
        TitleScreen _titleScreen;

        /// <summary>
        /// The main game instance.
        /// </summary>
        MainGame _mainGame;

        /// <summary>
        /// The game over screen instance.
        /// </summary>
        GameOverScreen _gameOverScreen;

        /// <summary>
        /// The you win screen instance.
        /// </summary>
        YouWinScreen _youWinScreen;

        /// <summary>
        /// Whether or not the game is in debug mode.
        /// </summary>
        public static bool DEBUG = false;

        /// <summary>
        /// Whether or not the background music plays.
        /// </summary>
        public static bool MUSIC = true;

        #endregion

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);

            //Set the window stuff.
            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 576;
            Window.Title = "Not Mega Man 7";
            Window.AllowUserResizing = true;
            IsMouseVisible = true;

            //Store the content folder's path.
            Content.RootDirectory = "Content";
        }

        #region Methods

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            //Start the title screen.
            StartTitleScreen();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            //Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            Content.Unload();
        }

        /// <summary>
        /// Starts the title screen.
        /// </summary>
        private void StartTitleScreen()
        {
            //Set the state and instantiate the title screen.
            _currentState = State.TitleScreen;
            _titleScreen = new TitleScreen(this);

            //Subscribe to the title screen's events.
            _titleScreen.OnGameStateQuit += new GameStateQuit(_gameState_OnGameStateQuit);
            _titleScreen.OnExitSelected += new ExitSelected(_titleScreen_OnExitSelected);

            //Initialise the title screen and load its content.
            _titleScreen.Initialise();
            _titleScreen.LoadContent(Content);
        }

        /// <summary>
        /// Starts the main game.
        /// </summary>
        /// <param name="gameDifficulty">The game's difficulty setting.</param>
        private void StartMainGame(GameDifficulty gameDifficulty)
        {
            //Set the state and instantiate the title screen.
            _currentState = State.MainGame;
            _mainGame = new MainGame(this, gameDifficulty);

            //Subscribe to the main game's events.
            _mainGame.OnGameStateQuit += new GameStateQuit(_gameState_OnGameStateQuit);

            //Initialise the title screen and load its content.
            _mainGame.Initialise();
            _mainGame.LoadContent(Content);
        }

        /// <summary>
        /// Starts the main game on the given level index.
        /// </summary>
        /// <param name="gameDifficulty">The game's difficulty setting.</param>
        /// <param name="levelIndex">The index of the level to start at.</param>
        private void StartMainGame(GameDifficulty gameDifficulty, int levelIndex)
        {
            //Set the state and instantiate the title screen.
            _currentState = State.MainGame;
            _mainGame = new MainGame(this, gameDifficulty, levelIndex);

            //Subscribe to the main game's events.
            _mainGame.OnGameStateQuit += new GameStateQuit(_gameState_OnGameStateQuit);

            //Initialise the title screen and load its content.
            _mainGame.Initialise();
            _mainGame.LoadContent(Content);
        }

        /// <summary>
        /// Starts the game over screen.
        /// </summary>
        private void StartGameOverScreen(GameDifficulty gameDifficulty)
        {
            //Set the state and instantiate the game over screen.
            _currentState = State.GameOverScreen;
            _gameOverScreen = new GameOverScreen(this, gameDifficulty);

            //Subscribe to the game over screen's events.
            _gameOverScreen.OnGameStateQuit += new GameStateQuit(_gameState_OnGameStateQuit);

            //Initialise the game over screen and load its content.
            _gameOverScreen.Initialise();
            _gameOverScreen.LoadContent(Content);
        }

        /// <summary>
        /// Starts the you win screen.
        /// </summary>
        private void StartYouWinScreen(GameDifficulty gameDifficulty)
        {
            //Set the state and instantiate the you win screen.
            _currentState = State.YouWinScreen;
            _youWinScreen = new YouWinScreen(this, gameDifficulty);

            //Subscribe to the you win screen's events.
            _youWinScreen.OnGameStateQuit += new GameStateQuit(_gameState_OnGameStateQuit);

            //Initialise the you win screen and load its content.
            _youWinScreen.Initialise();
            _youWinScreen.LoadContent(Content);
        }

        /// <summary>
        /// Ends the current state and unloads any content.
        /// </summary>
        private void EndCurrentState()
        {
            UnloadContent();

            switch (_currentState)
            {
                case State.TitleScreen:
                    //Lose the reference to the title screen and unsubscribe from its events.
                    _titleScreen.OnGameStateQuit -= _gameState_OnGameStateQuit;
                    _titleScreen.OnExitSelected -= _titleScreen_OnExitSelected;
                    _titleScreen = null;
                    break;
                case State.MainGame:
                    //Lose the reference to the main game and unsubscribe from its events.
                    _mainGame.OnGameStateQuit -= _gameState_OnGameStateQuit;
                    _mainGame = null;
                    break;
                case State.GameOverScreen:
                    //Lose the reference to the game over screen and unsubscribe from its events.
                    _gameOverScreen.OnGameStateQuit -= _gameState_OnGameStateQuit;
                    _gameOverScreen = null;
                    break;
                case State.YouWinScreen:
                    //Lose the reference to the game over screen and unsubscribe from its events.
                    _youWinScreen.OnGameStateQuit -= _gameState_OnGameStateQuit;
                    _youWinScreen = null;
                    break;
            }

            //Set the current state to none.
            _currentState = State.None;
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            switch (_currentState)
            {
                case State.TitleScreen:
                    _titleScreen.Update(gameTime);
                    break;
                case State.MainGame:
                    _mainGame.Update(gameTime);
                    break;
                case State.GameOverScreen:
                    _gameOverScreen.Update(gameTime);
                    break;
                case State.YouWinScreen:
                    _youWinScreen.Update(gameTime);
                    break;
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            switch (_currentState)
            {
                case State.TitleScreen:
                    _titleScreen.Draw(spriteBatch);
                    break;
                case State.MainGame:
                    _mainGame.Draw(spriteBatch);
                    break;
                case State.GameOverScreen:
                    _gameOverScreen.Draw(spriteBatch);
                    break;
                case State.YouWinScreen:
                    _youWinScreen.Draw(spriteBatch);
                    break;
            }

            base.Draw(gameTime);
        }

        #endregion

        #region Event Handles

        /// <summary>
        /// Handles the event called when the exit option on the title screen is selected.
        /// </summary>
        /// <param name="sender">The object calling the event.</param>
        /// <param name="e">Event arguments.</param>
        void _titleScreen_OnExitSelected(object sender, EventArgs e)
        {
            //Unload and exit.
            EndCurrentState();
            Exit();
        }

        /// <summary>
        /// Handles the event called when any game state is quit.
        /// </summary>
        /// <param name="sender">The game state that was quit.</param>
        /// <param name="e">Game state quit event arguments.</param>
        void _gameState_OnGameStateQuit(object sender, GameStateQuitEventArgs e)
        {
            EndCurrentState();
            MediaPlayer.Stop();

            //Set the state based on the event argument.
            switch (e.NextGameState)
            {
                case State.TitleScreen:
                    StartTitleScreen();
                    break;

                case State.MainGame:
                    //Determine if the game needs to start on a specific level.
                    if (e.MainGameLevel == GameStateQuitEventArgs.MostRecentLevel)
                        StartMainGame(e.GameDifficulty);
                    else
                        StartMainGame(e.GameDifficulty, e.MainGameLevel);
                    break;

                case State.GameOverScreen:
                    StartGameOverScreen(e.GameDifficulty);
                    break;

                case State.YouWinScreen:
                    StartYouWinScreen(e.GameDifficulty);
                    break;

                default:
                    throw new NotImplementedException();
            }
        }

        #endregion
    }
}
