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

#ifndef CONF_DISABLE_PLAYERKEYS
    #include "Player/PlayerKeys.hpp"
#endif

#include <fstream>

bool ConfReader::load(const std::string &filePath)
{
    m_confItems.clear();

    //Open file
    std::ifstream file;
    file.open(filePath.c_str(), std::ios::in);

    if (!file.fail())
    {
        //Get elements
        std::string lineBuffer;
        while (std::getline(file, lineBuffer))
        {
            std::string key, value;

            std::istringstream splitLine(lineBuffer);
            splitLine >> key; //The first word is the key
            std::getline(splitLine, value); //The remainder contains the value

            //At least the space delimiter plus one character
            if (value.size() > 1)
                m_confItems[key] = value.substr(1);
        }

        file.close();

        return true;
    }

    return false;
}

bool ConfReader::getItem(const std::string &elementKey, std::string &target) const
{
    std::map<std::string, std::string>::const_iterator it =
        m_confItems.find(elementKey);

    if (it != m_confItems.end())
    {
        target = it->second;
        return true;
    }

    return false;
}

#ifndef CONF_DISABLE_PLAYERKEYS
    void ConfReader::getPlayerKeysList(PlayerKeys &target) const
    {
        //Init variables
        std::string punch, kick, throwWeapon, jump, moveLeft, moveRight, crouch;

        if (getItem("punch", punch))
            target.setPunchKey(Key::fromKeyCode(punch));

        if (getItem("kick", kick))
            target.setKickKey(Key::fromKeyCode(kick));

        if (getItem("throw_weapon", throwWeapon))
            target.setThrowWeaponKey(Key::fromKeyCode(throwWeapon));

        if (getItem("jump", jump))
            target.setJumpKey(Key::fromKeyCode(jump));

        if (getItem("move_left", moveLeft))
            target.setMoveLeftKey(Key::fromKeyCode(moveLeft));

        if (getItem("move_right", moveRight))
            target.setMoveRightKey(Key::fromKeyCode(moveRight));

        if (getItem("crouch", crouch))
            target.setCrouchKey(Key::fromKeyCode(crouch));
    }
#endif
