#include "hilighter.h"


namespace {
    const static TStringBuf TEXT_TAG = "text";
    const static TStringBuf PRIORITY_TAG(TStringBuf("priority"));
    const static TStringBuf PRIORITY_ALL(TStringBuf("all"));
    const static TStringBuf PRIORITY_STRICT(TStringBuf("strict"));
    const static TStringBuf PRIORITY_PHRASE(TStringBuf("phrase"));
}

NJson::TJsonValue THilighter::Highlight(const char* value) {
    NJson::TJsonValue result;
    result.SetType(NJson::JSON_ARRAY);
    if (!value || !(*value)) {
        return result;
    }

    const char* textBeg = value;
    const char* i = value;
    TString currentPriority;
    for (; *i != 0; ++i) {
        if (*i == HILIGHT_MARK) {
            const char* p =  strchr(HILIGHTS, *(i + 1));
            if (!p)
                continue;
            if (i != textBeg) {
                NJson::TJsonValue& item = result.AppendValue(NJson::TJsonValue(NJson::JSON_MAP));
                if (!currentPriority.empty()) {
                    item[PRIORITY_TAG] = currentPriority;
                }
                item[TEXT_TAG] = TStringBuf(textBeg, i);
            }
            textBeg = ++i + 1;
            switch (*p) {
                case '(':
                    currentPriority = PRIORITY_ALL;
                    break;
                case '[':
                    currentPriority = PRIORITY_STRICT;
                    break;
                case '{':
                    currentPriority = PRIORITY_PHRASE;
                    break;
                case ')':
                case ']':
                case '}':
                    currentPriority = "";
                    break;
            }
        }
    }
    if (i > textBeg) {
        NJson::TJsonValue& item = result.AppendValue(NJson::TJsonValue(NJson::JSON_MAP));
        if (!currentPriority.empty()) {
            item[PRIORITY_TAG] = currentPriority;
        }
        item[TEXT_TAG] = TStringBuf(textBeg, i);
    }
    return result;
}
