#include "message_search_doc_ids.h"

#include <library/cpp/cgiparam/cgiparam.h>
#include <library/cpp/charset/wide.h>

#include <util/charset/utf8.h>

TMessageSearchDocIds::TMessageSearchDocIds(TString query, TSearchInfoProcessor* searchInfoProcessor)
    : Query(query)
    , SearchInfoProcessor(searchInfoProcessor)
{
    if (UTF8Detect(query.data(), query.size()) == UTF8) {
        query = WideToChar(UTF8ToWide(query), CODES_YANDEX);
    }
    else if (UTF8Detect(query.data(), query.size()) == ASCII) {
    } else {
        ERROR_LOG << "Incorrect query for delete. Unknown encoding detected." << Endl;
    }
    TCgiParameters params;
    params.Scan(Query);

    TString text = params.Get("text");
    params.ReplaceUnescaped("text", text);

    Query = "/?" + params.Print();
    Result.clear();
}

void TMessageSearchDocIds::AdditionalReserve(ui32 size) {
    if (!SearchInfoProcessor) {
        TGuard<TMutex> g(Mutex);
        Result.reserve(Result.capacity() + size);
    }
}

void TMessageSearchDocIds::AddResult(const TDocSearchInfo& result) {
    if (SearchInfoProcessor)
        SearchInfoProcessor->Process(result);
    else {
        TGuard<TMutex> g(Mutex);
        Result.push_back(result);
    }
}

int TMessageSearchDocIds::FinishPage(ui32 page) {
    return SearchInfoProcessor ? SearchInfoProcessor->FinishPage(page) : 0;
}
