/*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 "KeyboardKey.hpp"

#include "Tools/I18n.hpp" ///< _ macro for i18n
#include <sstream>

KeyboardKey::KeyboardKey() : KeyboardKey(SDL_SCANCODE_0) {}

KeyboardKey::KeyboardKey(SDL_Scancode keyboardKey) : m_key(keyboardKey) {}

bool KeyboardKey::keyPressed(const SDL_Event &event) const
{
    return event.type == SDL_KEYDOWN && event.key.keysym.scancode == m_key &&
        event.key.repeat == 0; //Ignore repeated key pressed events
}

bool KeyboardKey::keyReleased(const SDL_Event &event) const
{
    return event.type == SDL_KEYUP && event.key.keysym.scancode == m_key;
}

std::string KeyboardKey::getName() const
{
    const SDL_Keycode keyCode = SDL_GetKeyFromScancode(m_key);

    if (keyCode == SDLK_UP)
        return _(KeyArrowUp);
    else if (keyCode == SDLK_DOWN)
        return _(KeyArrowDown);
    else if (keyCode == SDLK_LEFT)
        return _(KeyArrowLeft);
    else if (keyCode == SDLK_RIGHT)
        return _(KeyArrowRight);
    else if (keyCode == SDLK_SPACE)
        return _(KeySpacebar);
    else if (keyCode == SDLK_BACKSPACE)
        return _(KeyBackspace);
    else if (keyCode == SDLK_RETURN)
        return _(KeyReturn);

    const char *keyName = SDL_GetKeyName(keyCode);
    if (keyName != nullptr)
        return std::string(keyName);

    return "?";
}

std::string KeyboardKey::getKeyCode() const
{
    std::ostringstream code;
    code << "kb" << +m_key;
    return code.str();
}

KeyboardKey KeyboardKey::layoutDependent(SDL_Keycode keycode)
{
    return KeyboardKey(SDL_GetScancodeFromKey(keycode));
}
