/* osgEarth
 * Copyright 2025 Pelican Mapping
 * MIT License
 */
#pragma once

#include <osgEarth/Common>
#include <osgEarth/ImageLayer>
#include <osgEarth/ElevationLayer>
#include <osgEarth/URI>
#include <osgEarth/Threading>
#include <osgEarth/Containers>
#include <osgEarth/GeoCommon>

/**
 * XYZ layers. These are general purpose tiled layers that conform
 * to a X/Y/Z prototype where Z is the tiling level and X/Y are the
 * tile offsets on that level.
 */

//! XYZ namespace contains support classes used to the Layers
namespace osgEarth { namespace XYZ
{
    /**
     * Underlying XYZ driver that does the actual I/O
     */
    class OSGEARTH_EXPORT Driver
    {
    public:
        Status open(
            const URI& uri,
            const std::string& format,
            const osgDB::Options* readOptions);

        ReadResult read(
            const URI& uri,
            const TileKey& key, 
            bool invertY,
            ProgressCallback* progress,
            const osgDB::Options* readOptions) const;

    protected:
        std::string _format;
        std::string _template;
        std::string _rotateChoices;
        std::string _rotateString;
        std::string::size_type _rotateStart, _rotateEnd;
        mutable std::atomic_int _rotate_iter;
    };
} }


namespace osgEarth
{
    /**
     * Image layer connected to a generic, raw tile service and accesible
     * via a URL template.
     *
     * The template pattern will vary depending on the structure of the data source.
     * Here is an example URL:
     *
     *    http://[abc].tile.openstreetmap.org/{z}/{x}/{y}.png
     *
     * {z} is the level of detail. {x} and {y} are the tile indices at that
     * level of detail. The [] delimiters indicate a URL "rotation"; for each
     * subsequent request, one and only one of the characters inside the []
     * will be used.
     *
     * XYZ accesses a "raw" data source and reads no metadata. Thus you must
     * expressly provide a geospatial Profile by calling setProfile() on the
     * layer before opening it or adding it to the Map. For example, for the
     * pattern above you might want a spherical mercator profile:
     *
     *    layer->setProfile( Profile::create(Profile::SPHERICAL_MERCATOR) );
     */
    class OSGEARTH_EXPORT XYZImageLayer : public ImageLayer
    {
    public:
        class OSGEARTH_EXPORT Options : public ImageLayer::Options
        {
        public:
            META_LayerOptions(osgEarth, Options, ImageLayer::Options);
            OE_OPTION(URI, url);
            OE_OPTION(bool, invertY, false);
            OE_OPTION(std::string, format, {});
            OE_OPTION(unsigned, minLevel, 0);
            OE_OPTION(unsigned, maxLevel, 10);
            Config getConfig() const override;
        private:
            void fromConfig(const Config& conf);
        };

    public:
        META_Layer(osgEarth, XYZImageLayer, Options, ImageLayer, XYZImage);

    public:
        //! Base URL for requests
        void setURL(const URI& value);
        const URI& getURL() const;

        //! Tiling profile (required)
        void setProfile(const Profile* profile) override;

        //! Whether to flip the Y axis for tile indexing
        void setInvertY(const bool& value);
        const bool& getInvertY() const;

        //! Data format to request from the service
        void setFormat(const std::string& value);
        const std::string& getFormat() const;

    public: // Layer
        
        //! Establishes a connection to the data
        virtual Status openImplementation() override;

        //! Creates a raster image for the given tile key
        virtual GeoImage createImageImplementation(const TileKey& key, ProgressCallback* progress) const override;

    protected: // Layer

        //! Called by constructors
        virtual void init();

    protected:

        //! Destructor
        virtual ~XYZImageLayer() { }

    private:
        XYZ::Driver _driver;
    };


    /**
     * Elevation layer that pulls from an XYZ encoded URL
     */
    class OSGEARTH_EXPORT XYZElevationLayer : public ElevationLayer
    {
    public:
        // Internal serialization options
        class OSGEARTH_EXPORT Options : public ElevationLayer::Options
        {
        public:
            META_LayerOptions(osgEarth, Options, ElevationLayer::Options);
            OE_OPTION(URI, url);
            OE_OPTION(bool, invertY, false);
            OE_OPTION(std::string, format, {});
            OE_OPTION(unsigned, minLevel, 0);
            OE_OPTION(unsigned, maxLevel, 10);
            OE_OPTION(std::string, elevationEncoding, {});
            OE_OPTION(bool, stitchEdges, false);
            OE_OPTION(RasterInterpolation, interpolation, INTERP_BILINEAR);
            Config getConfig() const override;
        private:
            void fromConfig(const Config& conf);
        };

    public:
        META_Layer(osgEarth, XYZElevationLayer, Options, ElevationLayer, XYZElevation);
        
        //! Base URL for requests
        void setURL(const URI& value);
        const URI& getURL() const;

        //! Tiling profile (required)
        void setProfile(const Profile* profile) override;

        //! Whether to flip the Y axis for tile indexing
        void setInvertY(const bool& value);
        const bool& getInvertY() const;

        //! Data format to request from the service
        void setFormat(const std::string& value);
        const std::string& getFormat() const;

        //! Encoding encoding type
        //! @param value Encoding type, one of "" (default), "mapbox", "terrarium"
        void setElevationEncoding(const std::string& value);
        const std::string& getElevationEncoding() const;

        //! Whether to stitch the edges of abutting tiles together to prevent gaps.
        //! Some elevation data is image based, and the side of one tile does not match
        //! the value on the correspond side of the abutting tile. This option will
        //! resample the data to make the edges match, for a small performance hit.
        //! @param value True to stitch edges (default is false)
        void setStitchEdges(const bool& value);
        const bool& getStitchEdges() const;

        //! Interpolation method to use when stitching edges = true.
        //! Default is INTERP_BILINEAR.
        void setInterpolation(const RasterInterpolation& value);
        const RasterInterpolation& getInterpolation() const;

    public: // Layer
        
        //! Establishes a connection to the XYZ data
        Status openImplementation() override;

        //! Creates a heightfield for the given tile key
        GeoHeightField createHeightFieldImplementation(const TileKey& key, ProgressCallback* progress) const override;

    protected: // Layer

        //! Called by constructors
        void init() override;

    protected:

        //! Destructor
        virtual ~XYZElevationLayer() { }

    private:
        osg::ref_ptr<XYZImageLayer> _imageLayer;
        mutable Util::LRUCache<TileKey, GeoImage> _stitchingCache{ 64u };
    };

} // namespace osgEarth

OSGEARTH_SPECIALIZE_CONFIG(osgEarth::XYZImageLayer::Options);
OSGEARTH_SPECIALIZE_CONFIG(osgEarth::XYZElevationLayer::Options);
