/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
 * Copyright 2015 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_ELEVATION_TERRAIN_LAYER_H
#define OSGEARTH_ELEVATION_TERRAIN_LAYER_H 1

#include <osgEarth/TerrainLayer>
#include <osg/MixinVector>

namespace osgEarth
{
    /**
     * Initialization and serialization options for an elevation layer.
     */
    class OSGEARTH_EXPORT ElevationLayerOptions : public TerrainLayerOptions
    {
    public:
        /** Constructs new elevation layer options. */
        ElevationLayerOptions( const ConfigOptions& options =ConfigOptions() );

        /** Constructs new elevation layer options, given the underlying driver options. */
        ElevationLayerOptions( const std::string& name, const TileSourceOptions& driverOptions );

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

        optional<bool>& offset() { return _offset; }
        const optional<bool>& offset() const { return _offset; }

        /** Policy for dealing with NO_DATA values in elevation */
        optional<ElevationNoDataPolicy>& noDataPolicy() { return _noDataPolicy; }
        const optional<ElevationNoDataPolicy>& noDataPolicy() const { return _noDataPolicy; }

    public:
        virtual Config getConfig() const { return getConfig(false); }
        virtual Config getConfig( bool isolate ) const;
        virtual void mergeConfig( const Config& conf );
        
    private:
        void fromConfig( const Config& conf );
        void setDefaults();

        optional<bool>                  _offset;
        optional<ElevationNoDataPolicy> _noDataPolicy;
    };

    //--------------------------------------------------------------------

    /**
     * Callback for receiving notification of property changes on an ElevationLayer.
     */
    struct ElevationLayerCallback : public TerrainLayerCallback
    {
        //TODO
    };

    typedef void (ElevationLayerCallback::*ElevationLayerCallbackMethodPtr)(class ElevationLayer* layer);

    typedef std::list< osg::ref_ptr<ElevationLayerCallback> > ElevationLayerCallbackList;


    //--------------------------------------------------------------------

    /**
     * A map terrain layer containing elevation grid heightfields.
     */
    class OSGEARTH_EXPORT ElevationLayer : public TerrainLayer
    {
    public:
        /**
         * Constructs a new elevation layer with the specified options. It expects
         * the layer options to contain a reference to the neccesary driver options.
         */
        ElevationLayer( const ElevationLayerOptions& options );

        /**
         * Constructs a new elevation layer with the specific name and driver options.
         * The layer will load its driver by using the tilesource options.
         */
        ElevationLayer( const std::string& name, const TileSourceOptions& driverOptions );

        /**
         * Constructs a new elevation layer with the specified layer options and with a custom
         * TileSource instance created by the user.
         */
        ElevationLayer( const ElevationLayerOptions& options, TileSource* tileSource );

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

        /** Gets the initialization options with which the layer was created. */
        const ElevationLayerOptions& getElevationLayerOptions() const { return _runtimeOptions; }
        virtual const TerrainLayerOptions& getTerrainLayerRuntimeOptions() const { return _runtimeOptions; }

        /** Adds a property notification callback to this layer */
        void addCallback( ElevationLayerCallback* cb );

        /** Removes a property notification callback from this layer */
        void removeCallback( ElevationLayerCallback* cb );

    public: // methods

        /**
         * Creates a GeoHeightField for this layer that corresponds to the extents and LOD 
         * in the specified TileKey. The returned HeightField will always match the geospatial
         * extents of that TileKey.
         */
        virtual GeoHeightField createHeightField(
            const TileKey&    key,
            ProgressCallback* progress =0L );

        /**
         * Whether this layer contains offsets instead of absolute heights
         */
        bool isOffset() const {
            return _runtimeOptions.offset() == true;
        }

    protected:
        
        // creates a geoHF directly from the tile source
        osg::HeightField* createHeightFieldFromTileSource( 
            const TileKey&    key, 
            ProgressCallback* progress);

        // assembles tiles from a layer that is not in the same profile as the map, and
        // returns a single tile in the map's profile.
        osg::HeightField* assembleHeightFieldFromTileSource(
            const TileKey&     key,
            ProgressCallback*  progress );
        
        virtual std::string suggestCacheFormat() const;

    private:
        ElevationLayerOptions _runtimeOptions;

        ElevationLayerCallbackList _callbacks;
        virtual void fireCallback( TerrainLayerCallbackMethodPtr method );
        virtual void fireCallback( ElevationLayerCallbackMethodPtr method );

        mutable osg::ref_ptr<TileSource::HeightFieldOperation> _preCacheOp;

        TileSource::HeightFieldOperation* getOrCreatePreCacheOp();
        Threading::Mutex _mutex;

        void init();
    };


    /**
     * Vector of elevation layers, with added methods.
     */
    class OSGEARTH_EXPORT ElevationLayerVector : public osg::MixinVector< osg::ref_ptr<ElevationLayer> >
    {
    public:
        /**
         * Populates an existing height field (hf must already exist) with height
         * values from the elevation layers.
         */
        bool populateHeightField(
            osg::HeightField*      hf,
            const TileKey&         key,
            const Profile*         haeProfile,
            ElevationInterpolation interpolation,
            ProgressCallback*      progress ) const;

    public:
        /** Default ctor */
        ElevationLayerVector();

        /** Copy ctor */
        ElevationLayerVector(const ElevationLayerVector& rhs);

        /**
         * Sets a tile size that createHeightField will always return.
         * By default, it will return a heightfield whose tile size matches
         * that of the largest tile size found in the source data layers.
         */
        void setExpressTileSize( unsigned tileSize );

    private:
        optional<unsigned> _expressTileSize;        
    };

} // namespace osgEarth

#endif // OSGEARTH_ELEVATION_TERRAIN_LAYER_H
