#include "utils.h"

#include <set>

namespace maps {
namespace wiki {
namespace configs {
namespace editor {

namespace {

const std::set<char> PUNCTUATION_CHARS
{
    ',',
    ' ',
    '"',
    '\''
};

} // namespace

void deduplicatePunctuation(std::string& text)
{
    if (text.empty()) {
        return;
    }
    auto writePos = text.begin();
    char lastDup = 0;
    for (auto curChar: text) {
        bool candidate = PUNCTUATION_CHARS.count(curChar);
        if (!candidate || curChar != lastDup) {
            *writePos = curChar;
            ++writePos;
        }
        lastDup = candidate ? curChar : 0;
    }
    *writePos = 0;
    text.resize(writePos - text.begin());
}

std::string trimLeadingUTF8BOM(const std::string& original)
{
    const std::string& utf8BOM = "\xEF\xBB\xBF";
    auto itOrg = original.begin();
    auto itBOM = utf8BOM.begin();
    size_t offset = 0;
    while (itOrg != original.end() && *itOrg++ == *itBOM++) {
        if (itBOM == utf8BOM.end()) {
            itBOM = utf8BOM.begin();
            offset += utf8BOM.length();
        }
    }
    return
        offset
        ? original.substr(offset)
        : original;
}

} // editor
} // configs
} // wiki
} // maps
