/* osgEarth - Geospatial SDK for OpenSceneGraph
* Copyright 2018 Pelican Mapping
* MIT License
*/
#ifndef OSGEARTH_DRIVERS_MP_TERRAIN_ENGINE_TILE_NODE_REGISTRY
#define OSGEARTH_DRIVERS_MP_TERRAIN_ENGINE_TILE_NODE_REGISTRY 1

#include "Common"
#include "TileNode"
#include <osgEarth/Revisioning>
#include <osgEarth/Threading>
#include <osgEarth/ResourceReleaser>
#include <osgEarth/Terrain>
#include <OpenThreads/Atomic>
#include <map>
#include <set>

namespace osgEarth { namespace Drivers { namespace MPTerrainEngine
{
    using namespace osgEarth;

    /**
     * Holds a reference to each tile created by the driver.
     */
    class TileNodeRegistry : public osg::Referenced
    {
    public:
        typedef std::map< TileKey, osg::ref_ptr<TileNode> > TileNodeMap;

        // Prototype for a locked tileset operation (see run)
        struct Operation {
            virtual void operator()(TileNodeMap& tiles) =0;
        };
        struct ConstOperation {
            virtual void operator()(const TileNodeMap& tiles) const =0;
        };

        // Operation that runs when another node enters the registry.
        struct DeferredOperation {
            virtual void operator()(TileNode* requestingNode, TileNode* expectedNode) const =0;
        };

    public:
        TileNodeRegistry(const std::string& name, Terrain* terrainIF);

        /* Enabled revisioning on TileNodes, to support incremental update. */
        void setRevisioningEnabled(bool value);

        /**
         * Sets the revision of the map model - the registry will assign this
         * to TileNodes added with add().
         *
         * @param rev        Revision of map
         * @param setToDirty In addition to update the revision, immediately set
         *                   all tiles to dirty as well, effectively forcing an
         *                   update.
         */
        void setMapRevision( const Revision& rev, bool setToDirty =false );

        /** Map revision that the reg will assign to new tiles. */
        const Revision& getMapRevision() const { return _maprev; }

        /**
         * Marks all tiles intersecting the extent as dirty. If incremental
         * update is enabled, they will automatically reload.
         *
         * NOTE: Input extent SRS must match the terrain's SRS exactly.
         *       The method does not check.
         */
        void setDirty(const GeoExtent& extent, unsigned minLevel, unsigned maxLevel);

        /**
         * Sets the current cull traversal frame number so that tiles have
         * access to the information. Atomic.
         */
        void setTraversalFrame(unsigned frame) { _frameNumber.exchange(frame); }

        unsigned getTraversalFrame() const { return _frameNumber; }

        virtual ~TileNodeRegistry() { }

        /** Adds a tile to the registry */
        void add( TileNode* tile );

        /** Removes a tile */
        void remove( TileNode* tile );

        /** Finds a tile in the registry */
        bool get( const TileKey& key, osg::ref_ptr<TileNode>& out_tile );

        /** Finds a tile in the registry and then removes it. */
        bool take( const TileKey& key, osg::ref_ptr<TileNode>& out_tile );

        /** Whether there are tiles in this registry (snapshot in time) */
        bool empty() const;
        
        /** Runs an operation against the read-locked tile set. */
        void run( const ConstOperation& op ) const;

        /** Number of tiles in the registry. */
        unsigned size() const { return _tiles.size(); }

        /** Empty the registry, releasing all tiles. */
        void releaseAll(ResourceReleaser*);

    protected:

        bool                              _revisioningEnabled;
        Revision                          _maprev;
        std::string                       _name;
        TileNodeMap                       _tiles;
        OpenThreads::Atomic               _frameNumber;
        mutable Threading::Mutex          _tilesMutex;
        osg::observer_ptr<Terrain>        _terrain;

        typedef std::set<TileKey> TileKeySet;
        typedef std::map<TileKey, TileKeySet> Notifications;
        Notifications _notifications;

    private:
        /** Tells the registry to listen for the TileNode for the specific key
            to arrive, and upon its arrival, notifies the waiter. After notifying
            the waiter, it removes the listen request. (assumes lock held) */
        void startListeningFor(const TileKey& keyToWaitFor, TileNode* waiter);

        /** Removes a listen request set by startListeningFor (assumes lock held) */
        void stopListeningFor(const TileKey& keyToWairFor, TileNode* waiter);
    };

} } } // namespace osgEarth::Drivers::MPTerrainEngine

#endif // OSGEARTH_DRIVERS_MP_TERRAIN_ENGINE_TILE_NODE_REGISTRY
