using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Input;

namespace StrategicCombat
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    abstract class MenuScreen : GameScreen
    {

        #region Variables

        // Content manager.
        ContentManager content;

        // Xbox icons
        Texture2D aButtonTexture;
        Texture2D bButtonTexture;

        // Pc icons
        Texture2D enterButtonTexture;
        Texture2D escapeButtonTexture;

        // Menu entries.
        List<MenuEntry> menuEntries = new List<MenuEntry>();
        int selectedEntry = 0;
        string menuTitle;

        // Constant x and y offsets
        public const int xOffset = 128;
        public const int yOffset = 72;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        protected IList<MenuEntry> MenuEntries
        {
            get { return menuEntries; }
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Create a new menu screen.
        /// </summary>
        public MenuScreen(string menuTitle)
        {
            this.menuTitle = menuTitle;

            TransitionOnTime = TimeSpan.FromSeconds(0.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }

        /// <summary>
        /// Loads graphics content for this screen.
        /// </summary>
        public override void LoadContent()
        {

            // Create a content manager.
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            // Load textures.
            aButtonTexture = content.Load<Texture2D>("MenuAssets/a");
            bButtonTexture = content.Load<Texture2D>("MenuAssets/b");
            enterButtonTexture = content.Load<Texture2D>("MenuAssets/enter");
            escapeButtonTexture = content.Load<Texture2D>("MenuAssets/escape");

        }

        /// <summary>
        /// Unloads graphics content for this screen.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
        }

        #endregion

        #region Handle Input

        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput(InputState input)
        {
            // Move to the previous menu entry?
            if (input.IsMenuUp(ControllingPlayer))
            {
                selectedEntry--;

                if (selectedEntry < 0)
                    selectedEntry = menuEntries.Count - 1;
            }

            // Move to the next menu entry?
            if (input.IsMenuDown(ControllingPlayer))
            {
                selectedEntry++;

                if (selectedEntry >= menuEntries.Count)
                    selectedEntry = 0;
            }

            // Accept or cancel the menu? We pass in our ControllingPlayer, which may
            // either be null (to accept input from any player) or a specific index.
            // If we pass a null controlling player, the InputState helper returns to
            // us which player actually provided the input. We pass that through to
            // OnSelectEntry and OnCancel, so they can tell which player triggered them.
            PlayerIndex playerIndex;

            if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
            {
                OnSelectEntry(selectedEntry, playerIndex);
            }
            else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
            {
                OnCancel(playerIndex);
            }
        }


        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
        {
            menuEntries[entryIndex].OnSelectEntry(playerIndex);
        }


        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel(PlayerIndex playerIndex)
        {
            ExitScreen();
        }


        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, PlayerIndexEventArgs e)
        {
            OnCancel(e.PlayerIndex);
        }


        #endregion

        #region Update and Draw


        /// <summary>
        /// Allows the screen the chance to position the menu entries. By default
        /// all menu entries are lined up in a vertical list, centered on the screen.
        /// </summary>
        protected virtual void UpdateMenuEntryLocations()
        {
            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            // start at Y = 175; each X value is generated per entry
            Vector2 position = new Vector2(0f, 170f);

            // update each menu entry's location in turn
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];
                
                // each entry is to be centered horizontally
                position.X = xOffset + 5;

                if (ScreenState == ScreenState.TransitionOn)
                    position.X -= transitionOffset * 256;
                else
                    position.X += transitionOffset * 512;

                // set the entry's position
                menuEntry.Position = position;

                // move down for the next entry the size of this entry
                position.Y += menuEntry.GetHeight(this);
            }

        } // End of the UpdateMenuEntryLocations method.

        /// <summary>
        /// Updates the menu screen.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Update each nested MenuEntry object.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);

                menuEntries[i].Update(this, isSelected, gameTime);
            }

        } // End of the Update method.


        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // Make sure our entries are in the right place before we draw them
            UpdateMenuEntryLocations();

            GraphicsDevice graphics = ScreenManager.GraphicsDevice;
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            Texture2D frameTexture = ScreenManager.blankTexture;
            SpriteFont font = ScreenManager.Font;

            spriteBatch.Begin();

            // Draw a rectangle for the game title
            spriteBatch.Draw(frameTexture, new Rectangle(0, yOffset, 1280, 68), Color.Orange * TransitionAlpha);

            // Draw each menu entry in turn.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];

                bool isSelected = IsActive && (i == selectedEntry);

                menuEntry.Draw(this, isSelected, gameTime);
            }

            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            // Draw the menu title centered on the screen
            Vector2 titlePosition = new Vector2(xOffset, yOffset + 10);
            float titleScale = 2f;
            Vector2 titleOrigin = Vector2.Zero;
            Color titleColor = Color.White * TransitionAlpha;

            titlePosition.Y -= transitionOffset * 100;

            // Dark gray shadow
            spriteBatch.DrawString(font, menuTitle, new Vector2(titlePosition.X + 1, titlePosition.Y + 1), Color.Gray * TransitionAlpha, 0,
                                   titleOrigin, titleScale, SpriteEffects.None, 0);

            // White text
            spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0, titleOrigin, titleScale, SpriteEffects.None, 0);

            // Draw a rectangle for buttons and keys
            spriteBatch.Draw(frameTexture, new Rectangle(0, 598, 1280, 48), Color.Orange * TransitionAlpha);

            // Button panel
            float buttonTextScale = 1.25f;
            String selectText = "Select";
            String backText = "Back";
            float selectStringSize = xOffset + 32 + 40 + (font.MeasureString(selectText).X * buttonTextScale) + 5;

#if (!XBOX360)

            // Draw select key with text (enter button)
            spriteBatch.Draw(enterButtonTexture, new Vector2(xOffset, 720 - yOffset - 42), Color.White * TransitionAlpha);

            spriteBatch.DrawString(font, selectText, new Vector2(xOffset + 41, 720 - yOffset - 40), Color.DarkGray * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);
            spriteBatch.DrawString(font, selectText, new Vector2(xOffset + 40, 720 - yOffset - 41), Color.White * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);

            // Draw back button with text (esc button)
            spriteBatch.Draw(escapeButtonTexture, new Vector2(selectStringSize, 720 - yOffset - 42), Color.White * TransitionAlpha);

            spriteBatch.DrawString(font, backText, new Vector2(selectStringSize + 41, 720 - yOffset - 40), Color.DarkGray * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);
            spriteBatch.DrawString(font, backText, new Vector2(selectStringSize + 40, 720 - yOffset - 41), Color.White * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);
#endif

#if (XBOX360)

            // Draw select key with text (a button)
            spriteBatch.Draw(aButtonTexture, new Vector2(xOffset, 720 - yOffset - 42), Color.White * TransitionAlpha);

            spriteBatch.DrawString(font, selectText, new Vector2(xOffset + 41, 720 - yOffset - 40), Color.DarkGray * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);
            spriteBatch.DrawString(font, selectText, new Vector2(xOffset + 40, 720 - yOffset - 41), Color.White * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);

            // Draw back button with text (b button)
            spriteBatch.Draw(bButtonTexture, new Vector2(selectStringSize, 720 - yOffset - 42), Color.White * TransitionAlpha);

            spriteBatch.DrawString(font, backText, new Vector2(selectStringSize + 41, 720 - yOffset - 40), Color.DarkGray * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);
            spriteBatch.DrawString(font, backText, new Vector2(selectStringSize + 40, 720 - yOffset - 41), Color.White * TransitionAlpha, 0,
                                   Vector2.Zero, buttonTextScale, SpriteEffects.None, 0);
#endif

            spriteBatch.End();

        } // End of the Draw method.

        #endregion

    } // End of class

} // End of namespace
