<%--
    Copyright (C) 2024 The Qt Company Ltd.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
    See the License for the specific language governing permissions and
    limitations under the License.
--%>

@import org.qtproject.qt.qtjenny.JteData
@import org.qtproject.qt.qtjenny.Constants

@param jteData: JteData

${Constants.AUTO_GENERATE_NOTICE}
#ifndef ${jteData.namespaceHelper.fileNamePrefix}${jteData.simpleClassName}Interface_H
#define ${jteData.namespaceHelper.fileNamePrefix}${jteData.simpleClassName}Interface_H

#include <QJniObject>
#include <QJniArray>
#include <QString>
#include <cmath>
#include <functional>
#include <vector>
#include <nativedispatch.h>

${jteData.namespaceHelper.beginNamespace()}
class ${jteData.simpleClassName}Interface : public NativeInterface {
private:
    struct qt_MethodReturn {bool matched; jobject result;};
    QJniObject m_jniObject;
    static constexpr double NaN = NAN;
    std::vector<std::function<qt_MethodReturn(jstring, jobjectArray)>> m_dispatch;
public:
    static constexpr auto FULL_CLASS_NAME = "${jteData.slashClassName}";
    QJniObject getJniObject() const {return m_jniObject;}
    const QJniObject* operator->() const {return &m_jniObject;}
    template <class T> operator T() {return m_jniObject.object<T>();}

    QJniObject qt_getProxy(const char* handlerClassName) {
      QJniEnvironment env;
      jlong nativeHandle = reinterpret_cast<jlong>(static_cast<NativeInterface*>(this));

      QJniObject handler(handlerClassName, nativeHandle);

      jclass interfaceClass = env.findClass(FULL_CLASS_NAME);
      QJniArray<jclass> ifaceArray(1);
      ifaceArray.setValue(0, interfaceClass);
      QJniObject handlerClass = handler.callObjectMethod<jclass>("getClass");
      QJniObject classLoader = handlerClass.callObjectMethod("getClassLoader", "()Ljava/lang/ClassLoader;");

      QJniObject proxy = QJniObject::callStaticObjectMethod(
        "java/lang/reflect/Proxy",
        "newProxyInstance",
        "(Ljava/lang/ClassLoader;[Ljava/lang/Class;Ljava/lang/reflect/InvocationHandler;)Ljava/lang/Object;",
        classLoader.object<jobject>(),
        ifaceArray.arrayObject(),
        handler.object<jobject>()
      );
      return proxy;
    }

    jobject qt_invoke(jstring method, jobjectArray args) override {
       for (auto&& x : m_dispatch) {
         qt_MethodReturn res = x(method, args);
         if (res.matched)
           return res.result;
       }
       return nullptr;
    }

