/*Copyright (C) 2010-2023 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"

void InputMonitor::update(const SDL_Event &event, Uint8 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)
    {  //AXIS
        //Initialization
        if (m_previousAxis.count(event.jaxis.axis) == 0)
            m_previousAxis[event.jaxis.axis] = AxisState::Centered;

        m_previousAxis[event.jaxis.axis] =
            JoyAxisKey::axisStateFromSDLCode(event.jaxis.value);
    }
}

bool InputMonitor::wasPressed(const SDL_Event &event, const Key &key,
                              Uint8 deviceID) const
{
    Key::Type keyType = key.getType();

    if (keyType == Key::Type::Keyboard)
        return key.buttonPressed(event);
    else if (keyType == Key::Type::JoyButton)
        return key.buttonPressed(event, deviceID);
    else if (keyType == Key::Type::JoyHat)
        return key.hatPressed(event, deviceID, m_previousHat);
    else if (keyType == Key::Type::JoyAxis)
        return key.axisPressed(event, deviceID, m_previousAxis);

    return false;
}

bool InputMonitor::wasReleased(const SDL_Event &event, const Key &key,
                               Uint8 deviceID) const
{
    Key::Type keyType = key.getType();

    if (keyType == Key::Type::Keyboard)
        return key.buttonReleased(event);
    else if (keyType == Key::Type::JoyButton)
        return key.buttonReleased(event, deviceID);
    else if (keyType == Key::Type::JoyHat)
        return key.hatReleased(event, deviceID, m_previousHat);
    else if (keyType == Key::Type::JoyAxis)
        return key.axisReleased(event, deviceID, m_previousAxis);

    return false;
}
