/* osgEarth
 * Copyright 2025 Pelican Mapping
 * MIT License
 */

#ifndef OSGEARTH_MBTILES_H
#define OSGEARTH_MBTILES_H

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

/**
 * MBTiles - MapBox tile storage specification using SQLite3
 * https://github.com/mapbox/mbtiles-spec
 */

//! Namespace for internal driver classes
namespace osgEarth { namespace MBTiles
{
    /**
     * MBTiles serialization data
     */
    class OSGEARTH_EXPORT Options
    {
    public:
        OE_OPTION(URI, url);
        OE_OPTION(std::string, format);
        OE_OPTION(bool, compress);
        void readFrom(const Config&);
        void writeTo(Config&) const;
    };

    /**
     * Underlying driver for reading/writing an MBTiles database
     */
    class OSGEARTH_EXPORT Driver
    {
    public:
        Driver();
        virtual ~Driver();

        Status open(
            const std::string& name,
            const Options& options,
            bool isWritingRequested,
            const optional<std::string>& format,
            osg::ref_ptr<const Profile>& profile,
            DataExtentList& dataExtents,
            const osgDB::Options* readOptions);

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

        Status write(
            const TileKey& key,
            const osg::Image* image,
            ProgressCallback* progress);

        Status write(
            const TileKey& key,
            const osg::HeightField* hf,
            ProgressCallback* progress);

        osg::Image* encode(
            const TileKey& key,
            const osg::Image* image,
            ProgressCallback* progress);

        void setDataExtents(const DataExtentList&);

        bool getMetaData(const std::string& name, std::string& value);
        bool putMetaData(const std::string& name, const std::string& value);

    private:
        struct PerThreadData
        {
            void* database = nullptr;
            void* selectTileStmt = nullptr;
            void* selectMetaDataStmt = nullptr;

            ~PerThreadData();
        };

        PerThreadData& getPerThreadData() const;

        void* _database;
        mutable Util::PerThread<PerThreadData> _perThreadData;
        mutable unsigned _minLevel;
        mutable unsigned _maxLevel;
        osg::ref_ptr< osg::Image> _emptyImage;
        osg::ref_ptr<osgDB::ReaderWriter> _rw;
        osg::ref_ptr<const osgDB::Options> _dbOptions;
        osg::ref_ptr<osgDB::BaseCompressor> _compressor;
        std::string _tileFormat;
        std::string _fullFilename;
        bool _forceRGB;
        std::string _name;

        // protects the shared write/metadata connection and mutable level metadata.
        mutable std::mutex _mutex;

        bool createTables();
        void computeLevels();
        int readMaxLevel();
        void closeDatabase();
    };
} }

//........................................................................

namespace osgEarth
{
    /**
     * Image layer connected to a TMS (Tile Map Service) facility
     */
    class OSGEARTH_EXPORT MBTilesImageLayer : public ImageLayer
    {
    public: // serialization
        class OSGEARTH_EXPORT Options : public ImageLayer::Options, public MBTiles::Options {
        public:
            META_LayerOptions(osgEarth, Options, ImageLayer::Options);
            virtual Config getConfig() const;
        private:
            void fromConfig(const Config&);
        };

    public:
        META_Layer(osgEarth, MBTilesImageLayer, Options, ImageLayer, MBTilesImage);

    public:
        //! Base URL of TileCache endpoint
        void setURL(const URI& value);
        const URI& getURL() const;

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

        //! Whether to compress the data. This isn't necessary for formats that
        //! are already compressed, like JPEG
        void setCompress(const bool& value);
        const bool& getCompress() const;

    public: // Layer

        //! Establishes a connection to the database
        Status openImplementation() override;

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

        //! Writes a raster image for the given key (if the layer is open for writing)
        Status writeImageImplementation(const TileKey& key, const osg::Image* image, ProgressCallback* progress) const override;

        //! Writes a pre-encoded raster image for the given key (if the layer is open for writing)
        //! BE CAREFUL that the data is encoded in the format specified by this layer!
        Result<osg::ref_ptr<osg::Image>> encodeImageImplementation(const TileKey& key, const osg::Image* image, ProgressCallback* progress) const override;

        //! Assigns data extents to this layer (if open for writing).
        void setDataExtents(const DataExtentList&) override;

    public:
        //! Gets the value of the metadata key
        bool getMetaData(const std::string& name, std::string& value);

        //! Put the metadata key
        bool putMetaData(const std::string& name, const std::string& value);        

    protected: // Layer

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

        bool isWritingSupported() const override { return true; }

        bool isEncodingSupported() const override { return true; }

    protected:

        //! Destructor
        virtual ~MBTilesImageLayer() { }

    private:
        mutable MBTiles::Driver _driver;
    };

    /**
     * Elevation layer connected to a TMS (Tile Map Service) facility
     */
    class OSGEARTH_EXPORT MBTilesElevationLayer : public ElevationLayer
    {
    public: // serialization
        class OSGEARTH_EXPORT Options : public ElevationLayer::Options, public MBTiles::Options {
        public:
            META_LayerOptions(osgEarth, Options, ElevationLayer::Options);
            virtual Config getConfig() const;
        private:
            void fromConfig(const Config&);
        };

    public:
        META_Layer(osgEarth, MBTilesElevationLayer, Options, ElevationLayer, MBTilesElevation);

        //! Base URL of TileCache endpoint
        void setURL(const URI& value);
        const URI& getURL() const;

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

        //! Whether to compress the data. This isn't necessary for formats that
        //! are already compressed, like JPEG
        void setCompress(const bool& value);
        const bool& getCompress() const;

    public: // Layer

        //! Establishes a connection to the database
        virtual Status openImplementation() override;

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

        //! Writes a heightfield image for the given key (if the layer is open for writing)
        virtual Status writeHeightFieldImplementation(const TileKey& key, const osg::HeightField* hf, ProgressCallback* progress) const override;

        //! Assigns data extents to this layer (if open for writing).
        virtual void setDataExtents(const DataExtentList&) override;

    public:
        //! Gets the value of the metadata key
        bool getMetaData(const std::string& name, std::string& value);

        //! Put the metadata key
        bool putMetaData(const std::string& name, const std::string& value);

    protected: // Layer

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

        virtual bool isWritingSupported() const override { return true; }

    protected:

        //! Destructor
        virtual ~MBTilesElevationLayer() { }

    private:
        mutable MBTiles::Driver _driver;
    };
} // namespace osgEarth

OSGEARTH_SPECIALIZE_CONFIG(osgEarth::MBTilesImageLayer::Options);
OSGEARTH_SPECIALIZE_CONFIG(osgEarth::MBTilesElevationLayer::Options);

#endif // OSGEARTH_MBTILES_H
