#include "document_wrapper.h"

namespace NRTYServer {
    namespace NTrie {
        namespace {
            TStringBuf ParseKey(TStringBuf key, char delimiter, size_t prefixLevel, ui32& prefixSize) {
                Y_VERIFY(key.size() <= Max<ui32>());
                size_t from = 0;
                for (size_t i = 0; i <= prefixLevel; ++i) {
                    from = key.find(delimiter, from);
                    if (from == TStringBuf::npos) {
                        prefixSize = 0;
                        return {};
                    }
                    ++from;
                }
                prefixSize = from - 1;
                return TStringBuf{key.data() + from - 1, key.size() + 1 - from};
            }
        }

        TDocumentWrapper::TDocumentWrapper(NMetaProtocol::TDocument& document, char delimiter, size_t prefixLevel, const THashMap<TString, ui32>& suffixMap)
            : Document(&document)
        {
            auto suffix = ParseKey(Document->GetUrl(), delimiter, prefixLevel, PrefixSize);
            if (PrefixSize > 0) {
                Suffix = suffixMap.at(suffix);
            }
        }

        TStringBuf TDocumentWrapper::GetPrefix() const {
            return TStringBuf{Document->GetUrl().data(), PrefixSize};
        }

        ui32 TDocumentWrapper::GetSuffix() const {
            return Suffix;
        }

        const NMetaProtocol::TDocument& TDocumentWrapper::GetDocument() const {
            return *Document;
        }

        NMetaProtocol::TDocument& TDocumentWrapper::GetDocument() {
            return *Document;
        }

        void TDocumentWrapper::SetDocument(NMetaProtocol::TDocument& document) {
            Document = &document;
        }

        bool TDocumentWrapper::operator<(const TDocumentWrapper& rhs) const {
            int cmp = GetPrefix().compare(rhs.GetPrefix());
            return cmp < 0 || cmp == 0 && Suffix < rhs.Suffix;
        }
    }
}
