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

#ifndef OSGEARTHUTIL_MOUSE_COORDS_TOOL_H
#define OSGEARTHUTIL_MOUSE_COORDS_TOOL_H 1

#include <osgEarth/Common>
#include <osgEarth/Controls>
#include <osgEarth/Formatter>

#include <osgGA/GUIEventHandler>

namespace osgEarth {
    class MapNode;
}

namespace osgEarth { namespace Contrib
{
    using namespace osgEarth;
    using namespace osgEarth::Util;
    using namespace osgEarth::Util::Controls;

    /**
     * Tool that prints the map coordinates under the mouse into a 
     * LabelControl.
     */
    class OSGEARTH_EXPORT MouseCoordsTool : public osgGA::GUIEventHandler
    {
    public:
        struct Callback : public osg::Referenced
        {
            // called when valid map coordinates are found under the mouse
            virtual void set( const GeoPoint& coords, osg::View* view, MapNode* mapNode ) =0;

            // called when no map coords are found under the mouse
            virtual void reset( osg::View* view, MapNode* mapNode ) =0;

            virtual ~Callback() { }
        };

    public:
        /**
         * Constructs a new handler
         * @param label
         *      Label control that will accept the coordinate readout
         * @param mapNode
         *      Map node from which to query coordinates
         * @param label
         *     (optional) label control to use for readout (automatically installs
         *     a MouseCoordsLabelCallback)
         * @param formatter
         *     (optional) When used with the label, specifies a formatter to use
         *     for the readout.
         */
        MouseCoordsTool( MapNode* mapNode, LabelControl* label =0L, Formatter* formatter =0L );

        virtual ~MouseCoordsTool() { }

        /**
         * Adds a readout callback.
         */
        void addCallback( Callback* callback );


    public: // GUIEventHandler

        bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );

    protected:
        MapNode*      _mapNode;
        osg::NodePath _mapNodePath;
        typedef std::vector< osg::ref_ptr<Callback> > Callbacks;
        Callbacks _callbacks;
    };


    /**
     * A sample callback that will display the mouse coords in a LabelControl.
     */
    class OSGEARTH_EXPORT MouseCoordsLabelCallback : public MouseCoordsTool::Callback
    {
    public:
        MouseCoordsLabelCallback( LabelControl* label, Formatter* formatter =0L );

        virtual ~MouseCoordsLabelCallback() { }

        virtual void set( const GeoPoint& coords, osg::View* view, MapNode* mapNode );
        virtual void reset( osg::View* view, MapNode* mapNode );

    protected:
        osg::observer_ptr<LabelControl> _label;
        osg::ref_ptr<Formatter>         _formatter;
    };

} }

#endif // OSGEARTHUTIL_MOUSE_COORDS_TOOL_H
