#include "StringTable.h"

#include "../util/AppInterface.h"
#include "../util/MultiplayerCommon.h"
#include "../util/Directories.h"

#if defined(_MSC_VER)
  // HACK! this keeps VC.x from barfing when it sees "typedef __int64 int64_t;"
  // in boost/cstdint.h when compiling under windows
#  if defined(int64_t)
#    undef int64_t
#  endif
#endif
#include <boost/filesystem/fstream.hpp>

using namespace std;

namespace {
    void HandleNewlines(std::string& str)
    {
        std::string::size_type pos = 0;
        while ((pos = str.find("\\n", pos)) != std::string::npos) {
            str.replace(pos, 2, "\n");
        }
    }
}

// static(s)
const string StringTable::S_DEFAULT_FILENAME = "eng_stringtable.txt";
const string StringTable::S_ERROR_STRING = "ERROR: ";

// StringTable
StringTable::StringTable():
    m_filename(S_DEFAULT_FILENAME)
{ Load(); }

StringTable::StringTable(const string& filename):
    m_filename(filename)
{ Load(); }

StringTable::~StringTable()
{}

const string& StringTable::operator[] (std::string index) const
{
    static std::string error_retval;
    map<string, string>::const_iterator it = m_strings.find(index);
    return it == m_strings.end() ? error_retval = S_ERROR_STRING + index : it->second;
}

void StringTable::Load()
{
    string temp;
    string temp2;
    std::ifstream ifs;
    try {
        ifs.open(m_filename.c_str());
    } catch (const exception& e) {
        Logger().errorStream() << "Error opening StringTable file \"" << m_filename << "\": " << e.what();
        return;        // handle exception by showing error msg and then get out!
    }

    getline(ifs, m_language);

    //we now use 1 line for an identifier and one line per string
    while(ifs.peek() != EOF) {
        getline(ifs, temp);

        //continue reading until we reach a pertinent line
        // i.e. once that doesn't start with a # sign or a newline
        while (temp.empty() || temp[0] == '#') {
            // make sure we're not reading extraneous lines at the end of the file
            if (ifs.peek() == EOF) {
                return;
            }
            getline(ifs, temp);
        }
        getline(ifs, temp2);

        HandleNewlines(temp2);

        if (!m_strings.insert(make_pair(temp, temp2)).second) {
            //found a duplicate or invalid key
            Logger().errorStream() << "Duplicate string ID found: '" << (string)temp << "' in file: '" << m_filename << "'.  Ignoring duplicate.";
        } 
        /*else {
            Logger().debugStream() << "Inserted(" << (string)temp << ", " << string(temp2) << ")";
        }*/
    }
}

