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

ConfReader::ConfReader()
{
    
}

bool ConfReader::load(const std::string &filePath)
{
    //Open file
    std::ifstream file;
    file.open(filePath.c_str(), std::ios::in);
    
    if (!file.fail())
    {
        //Get elements
        std::string lineBuffer;
        while (getline(file, lineBuffer))
        {
            std::string key, value;
            
            std::istringstream splitLine(lineBuffer);
            splitLine >> key; //First word is key
            splitLine >> value; //Second is value
            
            m_confItems[key] = value;
        }
        
        file.close();
        
        return true;
    }
    
    return false;
}

bool ConfReader::getItem(const std::string &elementKey, std::string &target)
{
    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;
}

bool ConfReader::getIntItem(const std::string &elementKey, int &target)
{
    std::string requestedItem;
    
    if (getItem(elementKey, requestedItem))
    {
        int intItem;
        
        std::istringstream convertToInt(requestedItem);
        convertToInt >> intItem;
        
        if (!convertToInt.fail())
        {
            target = intItem;
            return true;
        }
        
        return false;
    }
    
    return false;
}

bool ConfReader::getBoolItem(const std::string &elementKey, bool &target)
{
    std::string requestedItem;
    
    if (getItem(elementKey, requestedItem))
    {
        bool boolItem;
        
        std::istringstream convertToBool(requestedItem);
        convertToBool >> boolItem;
        
        if (!convertToBool.fail())
        {
            target = boolItem;
            return true;
        }
        
        return false;
    }
    
    return false;
}

bool ConfReader::getKeyCodeItem(const std::string &elementKey, SDLKey &target)
{
    int requestedItem;
    
    if (getIntItem(elementKey, requestedItem))
    {
        target = static_cast<SDLKey>(requestedItem);
        return true;
    }
    
    return false;
}
