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

#ifndef OSGEARTH_NETWORK_MONITOR_H
#define OSGEARTH_NETWORK_MONITOR_H 1

#include <osgEarth/Common>
#include <map>
#include <unordered_map>
#include <osg/Timer>
#include <string>

namespace osgEarth {
    class OSGEARTH_EXPORT NetworkMonitor
    {
    public:
        struct Request
        {
            Request() :
                isComplete(false), count(0u)
            {
                startTime = osg::Timer::instance()->tick();
            }

            Request(const std::string& _uri, const std::string& _status) :
                isComplete(false)
            {
                uri = _uri;
                status = _status;
                startTime = osg::Timer::instance()->tick();
            }

            double getDuration()
            {
                if (isComplete)
                {
                    return osg::Timer::instance()->delta_m(startTime, endTime);
                }
                return osg::Timer::instance()->delta_m(startTime, osg::Timer::instance()->tick());
            }

            bool isComplete;
            std::string uri;
            std::string layer;
            std::string type;
            std::string status;
            std::string detail;
            osg::Timer_t startTime;
            osg::Timer_t endTime;
            unsigned count;
        };

        struct ScopedRequestLayer
        {
            ScopedRequestLayer(const std::string& layer) :
                _layer(layer)
            {
                NetworkMonitor::setRequestLayer(_layer);
            }

            ~ScopedRequestLayer()
            {
                NetworkMonitor::setRequestLayer("");
            }
            std::string _layer;
        };

        using Requests = std::map<unsigned long, Request>; // sorted
        using URICount = std::unordered_map<std::string, unsigned>;

        static unsigned long begin(const std::string& uri, const std::string& status, const std::string& type = "");
        static void end(unsigned long handle, const std::string& status, const std::string& detail = {});
        static void getRequests(Requests& out);
        static bool getEnabled();
        static void setEnabled(bool enabled);
        static void clear();
        static void saveCSV(Requests& requests, const std::string& filename);

        static void setRequestLayer(const std::string& name);
        static std::string getRequestLayer();
    };



}

#endif // OSGEARTH_NETWORK_MONITOR_H
