/* -*-c++-*- */
/* osgEarth - Geospatial SDK for OpenSceneGraph
 * Copyright 2008-2014 Pelican Mapping
 * http://osgearth.org
 *
 * osgEarth is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */
#ifndef OSGEARTH_REX_UNLOADER
#define OSGEARTH_REX_UNLOADER 1

#include "Common"

#include <osgEarth/ThreadingUtils>
#include <osgEarth/TileKey>
#include <osgEarth/ResourceReleaser>

#include <osg/Group>


namespace osgEarth { namespace Drivers { namespace RexTerrainEngine
{
    class TileNodeRegistry; // for UnloaderGroup


    /**
     * Pure interface class for a tile unloader. The Tile Unloader is 
     * responsible for removing unused tiles from the scene graph and
     * releasing any GL resources associated with them.
     */
    class Unloader
    {
    public:
        virtual void unloadChildren(const std::vector<TileKey>& keys) =0;
    };

    /**
     * Group-based tile unloader.
     */
    class UnloaderGroup : public osg::Group, public Unloader
    {
    public:
        UnloaderGroup(TileNodeRegistry* tiles);

        /** Sets the key count at which unloading will begin */
        void setThreshold(int t) { _threshold = t; }

        /** Service that will release GL objects on unloaded nodes. */
        void setReleaser(ResourceReleaser* releaser) { _releaser = releaser; }

    public: // Unloader

        void unloadChildren(const std::vector<TileKey>& keys);

    public: // osg::Node
        void traverse(osg::NodeVisitor& nv);

    protected:
        int                            _threshold;
        std::set<TileKey>              _parentKeys;
        TileNodeRegistry*              _tiles;
        osg::ref_ptr<ResourceReleaser> _releaser;
        mutable Threading::Mutex       _mutex;
    };

} } } // namespace osgEarth::Drivers::RexTerrainEngine


#endif // OSGEARTH_REX_UNLOADER
