/*Copyright (C) 2010-2020 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "InputMonitor.hpp"
#include "Key.hpp"

InputMonitor::InputMonitor()
{
    
}

void InputMonitor::update(const SDL_Event &event, int deviceID)
{
    /// HAT
    if (event.type == SDL_JOYHATMOTION && deviceID == event.jhat.which)
    {
        //Initialization.
        if (m_previousHat.count(event.jhat.hat) == 0)
            m_previousHat[event.jhat.hat] = HatState();
        
        m_previousHat[event.jhat.hat].fromSDLCode(event.jhat.value);
    }
    else if (event.type == SDL_JOYAXISMOTION && deviceID == event.jaxis.which) /// JOYSTICK
    {
        //Initialization.
        if (m_previousAxis.count(event.jaxis.axis) == 0)
            m_previousAxis[event.jaxis.axis] = AXIS_STATE_CENTERED;
        
        m_previousAxis[event.jaxis.axis] = JoyAxisKey::axisStateFromSDLCode(event.jaxis.value);
    }
}

bool InputMonitor::wasPressed(const SDL_Event &event, const Key &key, int deviceID) const
{
    if (key.m_type == KEY_UNDEFINED)
        return false;
    else if (key.m_type == KEY_KEYBOARD)
        return key.m_keyboardKey.keyPressed(event);
    else if (key.m_type == KEY_JOYBUTTON)
        return key.m_joyButtonKey.keyPressed(event, deviceID);
    else if (key.m_type == KEY_JOYHAT)
        return key.m_joyHatKey.keyPressed(event, deviceID, m_previousHat);
    else if (key.m_type == KEY_JOYAXIS)
        return key.m_joyAxisKey.keyPressed(event, deviceID, m_previousAxis);
    
    return false;
}

bool InputMonitor::wasReleased(const SDL_Event &event, const Key &key, int deviceID) const
{
    if (key.m_type == KEY_UNDEFINED)
        return false;
    else if (key.m_type == KEY_KEYBOARD)
        return key.m_keyboardKey.keyReleased(event);
    else if (key.m_type == KEY_JOYBUTTON)
        return key.m_joyButtonKey.keyReleased(event, deviceID);
    else if (key.m_type == KEY_JOYHAT)
        return key.m_joyHatKey.keyReleased(event, deviceID, m_previousHat);
    else if (key.m_type == KEY_JOYAXIS)
        return key.m_joyAxisKey.keyReleased(event, deviceID, m_previousAxis);
    
    return false;
}
