/* -*-c++-*- */
/* osgEarth - Geospatial SDK for OpenSceneGraph
 * Copyright 2020 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 OSGEARTHDRIVERS_DUKTAPE_ENGINE_H
#define OSGEARTHDRIVERS_DUKTAPE_ENGINE_H 1

#include <osgEarth/ScriptEngine>
#include <osgEarth/Script>
#include <osgEarth/Feature>
#include <osgEarth/Containers>
#include "duktape.h"

namespace osgEarth { namespace Drivers { namespace Duktape
{
    using namespace osgEarth;

    /**
     * JavaScript engine built on the Duktape embeddable Javascript
     * interpreter. http://duktape.org
     */
    class DuktapeEngine : public osgEarth::ScriptEngine
    {
    public:
        /** Construct the engine */
        DuktapeEngine(const ScriptEngineOptions& options);

        /** Report language support */
        bool supported(std::string lang) { 
            return osgEarth::toLower(lang).compare("javascript") == 0;
        }

        /** Run a javascript code snippet. */
        ScriptResult run(
            const std::string& code,
            osgEarth::Feature const* feature,
            osgEarth::FilterContext const* context) override;

        bool run(
            const std::string& code,
            const FeatureList& features,
            std::vector<ScriptResult>& results,
            FilterContext const* context) override;

    protected:
        virtual ~DuktapeEngine();

        struct Context
        {
            Context();
            ~Context();
            void initialize(const ScriptEngineOptions&, bool);
            duk_context* _ctx;
            osg::observer_ptr<const Feature> _feature;
            std::string _bytecodeSource;
            unsigned char* _bytecode;
            unsigned _bytecodeSize;
            unsigned _errorCount;
        };

        PerThread<Context> _contexts;

        const ScriptEngineOptions _options;

        bool compile(
            Context& c,
            const std::string& code,
            ScriptResult& result);
    };

} } } // namespace osgEarth::Drivers::Duktape

#endif // OSGEARTHDRIVERS_DUKTAPE_ENGINE_H
