/* osgEarth
* Copyright 2025 Pelican Mapping
* MIT License
*/
#ifndef OSGEARTH_TILEVISITOR_H
#define OSGEARTH_TILEVISITOR_H 1

#include <osgEarth/Common>
#include <osgEarth/TileHandler>
#include <osgEarth/Profile>
#include <osgEarth/Threading>
#include <osgEarth/Progress>
#include <osgEarth/rtree.h>
#include <chrono>

namespace osgEarth { namespace Util
{
    using namespace osgEarth;

    /**
    * Utility class that traverses a Profile and emits TileKey's based on a collection of extents and min/max levels
    */
    class OSGEARTH_EXPORT TileVisitor : public osg::Referenced
    {
    public:
        using HasDataCallback = std::function<bool(const TileKey&)>;

        TileVisitor();

        TileVisitor(TileHandler* handler);

        //! Sets the minimum level to visit
        void setMinLevel(const unsigned int& minLevel) {_minLevel = minLevel;}

        //! Gets the minimum level to visit
        const unsigned int getMinLevel() const {return _minLevel;}

        //! Sets the maximum level to visit
        void setMaxLevel(const unsigned int& maxLevel) {_maxLevel = maxLevel;}

        //! Gets the maximum level to visit
        const unsigned int getMaxLevel() const {return _maxLevel;}

        //! Add an extent of input tiles to visit.
        void addExtentToVisit( const GeoExtent& extent );

        //! Get the collection of all input extents to visit
        const std::vector< GeoExtent >& getExtentsToVisit() const {
            return _extentsToVisit;
        }

        //! Adds an entry to data extent index; this lets you assign 
        //! detailed data extents to the visitor.
        void addExtentToDataIndex(const GeoExtent& extent);

        virtual void run(const Profile* mapProfile);

        bool intersects( const GeoExtent& extent );

        bool hasData(const TileKey& key);

        void setTileHandler( TileHandler* handler );

        void setProgressCallback( ProgressCallback* progress );

        ProgressCallback* getProgressCallback() const { return _progress.get(); }

        void incrementProgress( unsigned int progress );

        void resetProgress();


    protected:

        void estimate();

        virtual bool handleTile( const TileKey& key );

        void processKey( const TileKey& key );

        unsigned int _minLevel;
        unsigned int _maxLevel;

        // An index of areas that might have data.  This is an accleration structure to avoid processing areas that might not have data.
        using DataIndex = RTree<unsigned, double, 2>;
        DataIndex _dataExtentIndex;

        // The extents to process
        std::vector< GeoExtent > _extentsToVisit;

        osg::ref_ptr< TileHandler > _tileHandler;

        osg::ref_ptr< ProgressCallback > _progress;

        osg::ref_ptr< const Profile > _profile;

        std::mutex _progressMutex;

        HasDataCallback _hasData;

        unsigned int _total;
        unsigned int _processed;
        std::chrono::steady_clock::time_point _lastProgressUpdate;
    };


    /**
    * A TileVisitor that pushes all of it's generated keys onto a 
    * JobArena queue and handles them in background threads.
    */
    class OSGEARTH_EXPORT MultithreadedTileVisitor: public TileVisitor
    {
    public:
        MultithreadedTileVisitor();

        MultithreadedTileVisitor( TileHandler* handler );

        unsigned int getNumThreads() const;
        void setNumThreads( unsigned int numThreads);

        virtual void run(const Profile* mapProfile);

    protected:

        virtual bool handleTile( const TileKey& key );

        unsigned int _numThreads;

        std::shared_ptr<jobs::jobgroup> _group;
    };


    typedef std::vector< TileKey > TileKeyList;


    /**
     * A list of TileKeys that you can serialize to a file
     */
    class OSGEARTH_EXPORT TaskList
    {
    public:
        TaskList(const Profile* profile);

        /**
         * Loads the tiles from the given file.
         */
        bool load( const std::string &filename);

        /**
         * Saves the tiles to the given file.
         */
        void save( const std::string& filename);

        /**
         * Gets the list of keys
         */
        TileKeyList& getKeys();

        const TileKeyList& getKeys() const;

    protected:
        TileKeyList _keys;
        osg::ref_ptr< const Profile > _profile;
    };

} } // namespace osgEarth

#endif // OSGEARTH_TRAVERSAL_DATA_H
