
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

using System;
using System.Xml;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace GE.Input
{
    /// <summary>
    /// A 360 pad.
    /// </summary>
    class Gamepad : Device
    {
        /// <summary>
        /// Maps between an input mode and the actions and then between inputs and game actions
        /// </summary
        private Dictionary<InputMode, Dictionary<InputAction, GameAction>> _actions;

        /// <summary>
        /// State of a 360 gamepad
        /// </summary>
        private GamePadState _gamepadState;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="gamepad">xml node of a gamepad</param>
        public Gamepad(XmlNode gamepad)
        {
            _actions = new Dictionary<InputMode, Dictionary<InputAction, GameAction>>();
            _gamepadState = GamePad.GetState(0);

            loadDevice(gamepad);
        }

        /// <summary>
        /// Load the mapping between actions and inputs for the 360 pad
        /// </summary>
        /// <param name="device">the device xml node</param>
        public override void loadDevice(XmlNode device)
        {
            //go throught avery game mode
            XmlNodeList modes = device.ChildNodes;
            foreach (XmlNode mode in modes)
            {
                if (mode.Name.CompareTo("mode") == 0)
                {
                    //create the action dictionnary for the new mode
                    InputMode imode = (InputMode)Enum.Parse(typeof(InputMode), mode.Attributes["name"].Value, true);
                    _actions[imode] = new Dictionary<InputAction, GameAction>();

                    //go throught every action
                    XmlNodeList actions = mode.ChildNodes;
                    foreach (XmlNode action in actions)
                    {
                        if (action.Name.CompareTo("action") == 0)
                        {
                            //create the new action
                            InputAction iaction = (InputAction)Enum.Parse(typeof(InputAction),
                            action.Attributes["inputAction"].Value, true);
                            GameAction gaction = (GameAction)Enum.Parse(typeof(GameAction),
                                action.Attributes["gameAction"].Value, true);

                            _actions[imode][iaction] = gaction;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Update the inputs and send messages to the world
        /// </summary>
        public override void update(bool bSendRelease)
        {
            if (bSendRelease)
                updateWithRelease();
            else
                updateWithoutRelease();

        }

        private void updateWithoutRelease()
        {
            const float THRESHOLD_LEFTPAD = 0.5f;
            const float THRESHOLD_TRIGGER = 0.5f;
            //update the game pad states
            _gamepadState = GamePad.GetState(0);

            //360 pad disconnected
            if (!_gamepadState.IsConnected)
                return; // do something

            //go throught all the buttons
            if (_gamepadState.Buttons.Start == ButtonState.Pressed) sendInputAction(InputAction.Start_Pressed, 0, 1, 0);

            if (_gamepadState.Buttons.A == ButtonState.Pressed)
                sendInputAction(InputAction.A, 0, 1, 0);

            if (_gamepadState.Buttons.B == ButtonState.Pressed)
                sendInputAction(InputAction.B, 0, 1, 0);

            if (_gamepadState.Buttons.X == ButtonState.Pressed)
                sendInputAction(InputAction.X, 0, 1, 0);

            if (_gamepadState.Buttons.Y == ButtonState.Pressed)
                sendInputAction(InputAction.Y, 0, 1, 0);

            if (_gamepadState.ThumbSticks.Left.X < -THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Left, 0, 1, 0);

            if (_gamepadState.ThumbSticks.Left.X > THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Right, 0, 1, 0);

            if (_gamepadState.ThumbSticks.Left.Y > THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Up, 0, 1, 0);

            if (_gamepadState.ThumbSticks.Left.Y < -THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Down, 0, 1, 0);

            if (_gamepadState.Triggers.Left > THRESHOLD_TRIGGER)
                sendInputAction(InputAction.LeftTrigger, 0, 1, 0);
        }

        private void updateWithRelease()
        {
            const float THRESHOLD_LEFTPAD = 0.5f;
            const float THRESHOLD_TRIGGER = 0.5f;
            //update the game pad states
            _gamepadState = GamePad.GetState(0);

            //360 pad disconnected
            if (!_gamepadState.IsConnected)
                return; // do something

            //go throught all the buttons
            if (_gamepadState.Buttons.Start == ButtonState.Pressed) sendInputAction(InputAction.Start_Pressed, 0, 1, 0);

            if (_gamepadState.Buttons.A == ButtonState.Pressed)
                sendInputAction(InputAction.A, 0, 1, 0);
            else
                sendInputAction(InputAction.A, 0, 0, 0);

            if (_gamepadState.Buttons.B == ButtonState.Pressed)
                sendInputAction(InputAction.B, 0, 1, 0);
            else
                sendInputAction(InputAction.B, 0, 0, 0);

            if (_gamepadState.Buttons.X == ButtonState.Pressed)
                sendInputAction(InputAction.X, 0, 1, 0);
            else
                sendInputAction(InputAction.X, 0, 0, 0);

            if (_gamepadState.Buttons.Y == ButtonState.Pressed)
                sendInputAction(InputAction.Y, 0, 1, 0);
            else
                sendInputAction(InputAction.Y, 0, 0, 0);

            if (_gamepadState.ThumbSticks.Left.X < -THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Left, 0, 1, 0);
            else
                sendInputAction(InputAction.ThumbStickLeft_Left, 0, 0, 0);

            if (_gamepadState.ThumbSticks.Left.X > THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Right, 0, 1, 0);
            else
                sendInputAction(InputAction.ThumbStickLeft_Right, 0, 0, 0);

            if (_gamepadState.ThumbSticks.Left.Y > THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Up, 0, 1, 0);
            else
                sendInputAction(InputAction.ThumbStickLeft_Up, 0, 0, 0);

            if (_gamepadState.ThumbSticks.Left.Y < -THRESHOLD_LEFTPAD)
                sendInputAction(InputAction.ThumbStickLeft_Down, 0, 1, 0);
            else
                sendInputAction(InputAction.ThumbStickLeft_Down, 0, 0, 0);

            if (_gamepadState.Triggers.Left > THRESHOLD_TRIGGER)
                sendInputAction(InputAction.LeftTrigger, 0, 1, 0);
            else
                sendInputAction(InputAction.LeftTrigger, 0, 0, 0);
        }

        /// <summary>
        /// Send message to the player
        /// </summary>
        /// <param name="action">Action to send</param>
        /// <param name="player">id of the player who gotta receive the message</param>
        private void sendInputAction(InputAction action, PlayerIndex player)
        {
            Input.Instance.sendInputAction( _actions[Input.Instance.Mode][action], 0);
        }

        /// <summary>
        /// Send a message to a player
        /// </summary>
        /// <param name="action">Action to send</param>
        /// <param name="player">player's id who gotta receive the message</param>
        /// <param name="a">first parameter</param>
        /// <param name="b">second parameter</param>
        private void sendInputAction(InputAction action, PlayerIndex player, float a, float b)
        {
            Input.Instance.sendInputAction(_actions[Input.Instance.Mode][action], 0, a, b);
        }

        /// <summary>
        /// Return if the 360 controller is connected
        /// </summary>
        public override bool IsConnected { get { return _gamepadState.IsConnected; } }
    }
}
