
/****************************************************************************/
/*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.IO;
using System.Xml;
using System.Collections.Generic;

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

using GE.Tools;
using GE.Message;
using GE.TimeClock;

namespace GE.Input
{
    /// <summary>
    /// Input Component. Handle all the input device and their updates. Also send the messages.
    /// </summary>
    class Input
    {
        /// <summary>
        /// Unique instance of the Input Component
        /// </summary>
        private static Input m_instance = new Input();

        /// <summary>
        /// Number of players.
        /// </summary>
        private int m_players;

        /// <summary>
        /// Input Mode.
        /// </summary>
        private InputMode m_mode;

        /// <summary>
        /// Maps input mode to receiver in the message system.
        /// </summary>
        private Dictionary<InputMode, MessageReceiver> m_receivers;

        /// <summary>
        /// List of the different devices used to retreive inputs
        /// </summary>
        //private List<Device> m_devices;

        private Device _device360Pad;

        private Device _deviceKeyboard;

        /// <summary>
        /// Time in ms when the last pause ended.
        /// </summary>
        private int m_pauseEnd;

        /// <summary>
        /// Unique instance of the Input Component
        /// </summary>
        public static Input Instance
        {
            get { return m_instance; }
        }

        /// <summary>
        /// Input Mode.
        /// </summary>
        public InputMode Mode
        {
            get
            {
                return m_mode;
            }
            set
            {
                m_mode = value;
                // send event somewhere ?
            }
        }

        /// <summary>
        /// Private constructor.
        /// </summary>
        private Input()
        {
            m_pauseEnd = 0;
            m_players = 0;
        }

        /// <summary>
        /// Initializes the Input component.
        /// </summary>
        /// <param name="players">number of players</param>
        public void init(string filename, int players)
        {
            m_players = players;

            loadFromXml(filename);

            // init modes
            m_receivers = new Dictionary<InputMode, MessageReceiver>();
            m_receivers[InputMode.Game] = MessageReceiver.World;
            m_receivers[InputMode.Gui] = MessageReceiver.Gui;
        }

        /// <summary>
        /// Load the xml file containing the definitions of inputs and actions
        /// </summary>
        /// <param name="filename"></param>
        private void loadFromXml(string filename)
        {
            //load the xml file
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(filename);
            }
            catch (FileNotFoundException e)
            {
                Logger.Instance.error(this, e, "Control file not found.");
            }

            //create the list of device
            //m_devices = new List<Device>();

            //go throught each device defined in the file
            XmlElement root = doc.DocumentElement;
            XmlNodeList devices = root.ChildNodes;
            foreach (XmlNode device in devices)
            {
                if (device.Name.CompareTo("device") == 0)
                {
                    if (device.Attributes["type"].Value.CompareTo("Gamepad") == 0)
                        _device360Pad = new Gamepad(device);
                    else if (device.Attributes["type"].Value.CompareTo("Keyboard") == 0)
                        _deviceKeyboard = new KeyBoard(device);
                }
            }
        }

        /// <summary>
        /// Updates the Input component.
        /// </summary>
        public void update()
        {
            if (m_pauseEnd > Clock.instance.millisecs)
                return;

            switch (Mode)
            {
                case InputMode.Game:
                    updateModeGame();
                    break;

                case InputMode.Gui:
                    updateModeGui();
                    break;
            }
                  
        }

        private void updateModeGame()
        {
            _device360Pad.update(true);
            if (!_device360Pad.IsConnected)
                _deviceKeyboard.update(true);   
        }

        private void updateModeGui()
        {
            _device360Pad.update(false);
            if (!_device360Pad.IsConnected)
                _deviceKeyboard.update(false);   
        }

        /// <summary>
        /// Sends a game action through the message system.
        /// </summary>
        /// <param name="action">input action</param>
        /// <param name="player">player index</param>
        public void sendInputAction(GameAction action, PlayerIndex player)
        {
            MessageSystem.Instance.pushMessage(MessageType.Input, m_receivers[m_mode],
                    (float)action, (float)player, 0f, 0f);
        }

        /// <summary>
        /// Sends a game action through the message system.
        /// </summary>
        /// <param name="action">input action</param>
        /// <param name="player">player index</param>
        /// <param name="a">value</param>
        /// <param name="b">value</param>
        public void sendInputAction(GameAction action, PlayerIndex player, float a, float b)
        {
            MessageSystem.Instance.pushMessage(MessageType.Input, m_receivers[m_mode],
                    (float)action, (float)player, a, b);
        }

        /// <summary>
        /// Set a new pause.
        /// </summary>
        /// <param name="ms">The length in milliseconds of the pause</param>
        public void pause(int ms)
        {
            m_pauseEnd = Clock.instance.millisecs + ms;
        }
    }
}
