package io.scanbot.sdk.reactnative;

import android.util.Log;

import app.cash.quickjs.QuickJs;

/**
 * This class is necessary in order to execute JavaScript callbacks natively in a
 * synchronous manner. This implementation relies on QuickJs, an open source lightweight
 * library that lets you synchronously run JavaScript code on Android, without having
 * to instantiate a WebView beforehand.
 * <p>
 * Engine: https://bellard.org/quickjs/
 * Android Wrapper: https://github.com/cashapp/quickjs-java
 */
public class JavaScriptEngine {

    // This allows us to define Java methods that can be called from the JS layer
    private interface NativeBridge {
        void log(String text);
    }

    // This maps console.log to the native log function implemented through the NativeBridge
    private final static String loggerScript = "const console={log:(text)=>{ScanbotSDK.log(text);}};";

    // Private Attributes
    private final NativeBridge nativeBridge;

    // Singleton Initializer
    private static JavaScriptEngine instance;

    public static JavaScriptEngine getInstance() {
        if (instance == null) {
            instance = new JavaScriptEngine();
        }
        return instance;
    }

    private JavaScriptEngine() {
        nativeBridge = new NativeBridge() {
            @Override
            public void log(String text) {
                Log.d("ScanbotSDK", String.format("[JS] %s", text));
            }
        };
    }

    // Sets up the NativeBridge interface and defines some context variables
    private boolean prepareContext(final QuickJs javaScriptEngine) {
        try {
            javaScriptEngine.set("ScanbotSDK", NativeBridge.class, nativeBridge);
            javaScriptEngine.evaluate(loggerScript);
        } catch (final Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
