/* osgEarth - Geospatial SDK for OpenSceneGraph
* Copyright 2018 Pelican Mapping
* MIT License
*/

#ifndef OSGEARTH_ENGINE_OSGTERRAIN_FILE_LOCATION_CALLBACK_H
#define OSGEARTH_ENGINE_OSGTERRAIN_FILE_LOCATION_CALLBACK_H 1

#include "MPTerrainEngineNode"
#include <osg/Version>
#include <osgEarth/Export>

#define USE_FILELOCATIONCALLBACK 1

#if USE_FILELOCATIONCALLBACK

namespace osgEarth { namespace Drivers { namespace MPTerrainEngine
{
    /**
     * A database pager callback that determines if the given filename is cached or not
     */
    class FileLocationCallback : public osgDB::FileLocationCallback
    {
    public:
        FileLocationCallback() { }

        /** dtor */
        virtual ~FileLocationCallback() { }

        Location fileLocation(const std::string& filename, const osgDB::Options* options)
        {
            Location result = REMOTE_FILE;

            unsigned int lod, x, y, id;
            sscanf(filename.c_str(), "%d/%d/%d.%d", &lod, &x, &y, &id);

            osg::ref_ptr<MPTerrainEngineNode> engine;
            MPTerrainEngineNode::getEngineByUID( (UID)id, engine );

            if ( engine.valid() )
            {
                const osgEarth::Profile* profile = engine->getMap()->getProfile();
                osgEarth::TileKey mapKey( lod, x, y, profile );

                result = LOCAL_FILE;

                MapFrame mapf( engine->getMap() );
                for( unsigned i=0; i<4; ++i )
                {
                    TileKey childKey = mapKey.createChildKey( i );
                    if ( !mapf.isCached( childKey ) )
                    {
                        result = REMOTE_FILE;
                        break;
                    }
                }
            }

            //OE_NOTICE << (result?"REMOTE":"LOCAL") << " - " << filename << std::endl;

            return result;
        }

        bool useFileCache() const { return false; }
    };

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

#endif // USE_FILELOCATIONCALLBACK

#endif //OSGEARTH_ENGINE_OSGTERRAIN_FILE_LOCATION_CALLBACK_H
