#include "disk_manager.h"

#include <saas/library/proto_helper/proto_helper.h>

#include <saas/rtyserver/components/prop/prop.fbs.h>
#include <saas/library/cgi/cgi.h>

namespace NRTYServer {
    namespace {
        class TStringTable {
        public:
            explicit TStringTable(const NFb::TStringTable& table)
            {
                Y_ENSURE(table.Offsets());
                Y_ENSURE(table.Data());
                Offsets = *table.Offsets();
                Data = {table.Data()->data(), table.Data()->size()};
            }

            size_t Size() const { return Offsets.size(); }

            TStringBuf operator[](size_t i) const {
                const auto start = Offsets[i];
                const auto end = (i + 1 < Offsets.size()) ? Offsets[i + 1] : Data.size();
                return {Data.data() + start, Data.data() + end};
            }

        private:
            TArrayRef<const uint32_t> Offsets;
            TStringBuf Data;
        };
    }

    void TPropDiskManager::WalkDocumentProperties(
            ui32 docId, std::function<void (TStringBuf, TStringBuf)>&& cont) const {
        const auto valueBuffer = FetchRawL2Data(docId);
        if (valueBuffer.Empty()) {
            return;
        }
        const auto properties = NFb::GetTPropertyMap(valueBuffer.Data());
        Y_ENSURE(properties->Keys());
        Y_ENSURE(properties->Values());
        const TStringTable keys{*properties->Keys()};
        const TStringTable values{*properties->Values()};
        Y_ENSURE(keys.Size() == values.Size());
        for (const size_t i: xrange(keys.Size())) {
            cont(keys[i], values[i]);
        }
    }
} // namespace NRTYServer
