#pragma once

#include <util/generic/fwd.h>
#include <util/generic/ptr.h>
#include <contrib/libs/mongo-c-driver/libmongoc/src/mongoc/mongoc.h>
#include <contrib/libs/mongo-c-driver/libbson/src/bson/bson.h>

namespace NJson {
    class TJsonValue;
}

namespace NUtil {
    class TMongoConnection;
    class TMongoGridFs;

    class TMongoCollection {
    public:
        using TPtr = TAtomicSharedPtr<TMongoCollection>;

        class TIterator {
        public:
            using TPtr = TAtomicSharedPtr<TIterator>;

            TIterator(mongoc_cursor_t* cursor, TMongoCollection* owner);
            bool IsValid() const;
            void Next();

            const NJson::TJsonValue& Get() const;
            ~TIterator();

        private:
            mongoc_cursor_t* Cursor;
            TMongoCollection* Owner;
            THolder<NJson::TJsonValue> Data;

        };

        TMongoCollection(TMongoConnection* connection, const TString& db, const TString& collection);
        TMongoCollection(TMongoGridFs* gridFs);
        TMongoCollection& Insert(const NJson::TJsonValue&);
        TMongoCollection& Update(const NJson::TJsonValue& query, const NJson::TJsonValue& doc);
        void Remove(const NJson::TJsonValue& query, bool removeAll);
        TIterator::TPtr Find(const NJson::TJsonValue& query);
        TIterator::TPtr Find(const NJson::TJsonValue& query, const TString& fields);

        ~TMongoCollection();

    private:
        void AddIter();
        void RemoveIter();

    private:
        mongoc_collection_t* Collection;
        ui64 AliveIters;
    };
}
