{#
// Template to call into rust. Variable names in `arg_list` should match up with arg lists
// passed to rust via `arg_list_lowered`.
//
// Generated locals sharing a scope with user argument names start with `_`; the invariant
// is on `JavaCodeOracle::var_name`.
#}

{%- macro to_ffi_call(func) -%}
    {%- match func.self_type() %}
    {%- when Some with (Type::Object { .. }) %}
    callWithHandle(_uniffiHandle -> {
        try {
    {% if func.return_type().is_some() %}
            return {%- call to_raw_ffi_call(func) %}{% endcall %};
    {% else %}
            {%- call to_raw_ffi_call(func) %}{% endcall %};
    {% endif %}
    {#- The wrap below exists only to launder a declared error, which is checked, across
        `Function.apply`. Rethrowing unchecked first keeps a method's exceptions identical to the
        same call made as a free function, which has no wrap at all. -#}
        } catch (java.lang.RuntimeException _uniffi_ex) {
            throw _uniffi_ex;
        } catch (java.lang.Exception _uniffi_ex) {
            throw new java.lang.RuntimeException(_uniffi_ex);
        }
    })
    {% else %}
        {%- call to_raw_ffi_call(func) %}{% endcall %}
    {% endmatch %}
{%- endmacro %}

{%- macro to_raw_ffi_call(func) -%}
    {%- match func.return_type() %}
    {%- when Some(return_type) %}
    {%- let prim_suffix = return_type|primitive_call_suffix %}
    {%- let ffi_type = return_type|ffi_type %}
    {%- when None %}
    {%- endmatch %}
    {%- match func.throws_type() %}
    {%- when Some(e) %}
    {%- if e|is_external(ci) %}
    UniffiHelpers.uniffiRustCallWithError{% match func.return_type() %}{%- when Some(return_type) %}{{ return_type|primitive_call_suffix }}{% when None %}{% endmatch %}(new {{ e|class_name_from_type(ci) }}ExternalErrorHandler(),
    {%- else %}
    UniffiHelpers.uniffiRustCallWithError{% match func.return_type() %}{%- when Some(return_type) %}{{ return_type|primitive_call_suffix }}{% when None %}{% endmatch %}(new {{ e|type_name(ci, config) }}ErrorHandler(),
    {%- endif %}
    {%- else %}
    UniffiHelpers.uniffiRustCall{% match func.return_type() %}{%- when Some(return_type) %}{{ return_type|primitive_call_suffix }}{% when None %}{% endmatch %}(
    {%- endmatch %} (_allocator, _status) -> {
    {#- Only the wrapper is conditional: askama inlines a `call` at each site and emits both `if`
        branches, so duplicating the invocation here doubles it in every generated call site. -#}
    {%- if func|has_borrowed_bytes_args %}
        try {
    {%- endif %}
        {% if func.return_type().is_some() %}return {% endif %}UniffiLib.{{ func.ffi_func().name() }}(
            {%- match func.return_type() %}
            {%- when Some(return_type) %}
            {%- let ffi_type = return_type|ffi_type %}
            {%- if ffi_type.borrow()|ffi_type_is_struct %}_allocator, {% endif %}
            {%- when None %}
            {%- endmatch %}
            {%- match func.self_type() %}
            {%- when Some with (Type::Object { .. }) %}_uniffiHandle,
            {%- when Some(t) %}{{ t|lower_fn(config, ci) }}(this),
            {%- when None %}
            {%- endmatch %}
            {% if func.arguments().len() != 0 %}{% call arg_list_lowered(func) %}{% endcall -%}, {% endif -%}
            _status);
    {%- if func|has_borrowed_bytes_args %}
        } finally {
            {{ func|reachability_fences }}
        }
    {%- endif %}
    })
{%- endmacro -%}

{%- macro func_decl(func_decl, annotation, callable, indent) %}
    {%- if callable.is_async() %}
    {{ callable|async_docstring(indent, false) }}
    {%- if annotation != "" %}
    @{{ annotation }}
    {% endif %}
    {#- Async methods use CompletableFuture<T> which requires boxed types -#}
    {#- No-executor overload - defaults to ForkJoinPool.commonPool(), delegates to Executor version -#}
    {{ func_decl }} java.util.concurrent.CompletableFuture<{% match callable.return_type() -%}{%- when Some with (return_type) -%}{{ return_type|boxed_type_name(ci, config) }}{%- when None %}java.lang.Void{%- endmatch %}> {{ callable.name()|fn_name }}(
        {%- call arg_list(callable, !callable.self_type().is_some()) %}{% endcall -%}
    ){
        return {{ callable.name()|fn_name }}({% call arg_name_list(callable) %}{% endcall %}{% if !callable.arguments().is_empty() %}, {% endif %}java.util.concurrent.ForkJoinPool.commonPool());
    }

    {#- With-executor overload - does the actual async work -#}
    {{ callable|async_docstring(indent, true) }}
    {{ func_decl }} java.util.concurrent.CompletableFuture<{% match callable.return_type() -%}{%- when Some with (return_type) -%}{{ return_type|boxed_type_name(ci, config) }}{%- when None %}java.lang.Void{%- endmatch %}> {{ callable.name()|fn_name }}(
        {%- call arg_list(callable, !callable.self_type().is_some()) %}{% endcall -%}{% if !callable.arguments().is_empty() %}, {% endif %}java.util.concurrent.Executor _uniffiExecutor
    ){
        return {% call call_async(callable) %}{% endcall %};
    }
    {%- else -%}
    {%- call docstring(callable, indent) %}{% endcall %}
    {%- if annotation != "" %}
    @{{ annotation }}
    {% endif %}
    {#- Sync methods can use primitives for return types -#}
    {{ func_decl }} {% match callable.return_type() -%}{%- when Some with (return_type) -%}{{ return_type|type_name_for_field(ci, config) }}{%- when None %}void{%- endmatch %} {{ callable.name()|fn_name }}(
        {%- call arg_list(callable, !callable.self_type().is_some()) %}{% endcall -%}
    ) {% match callable.throws_type() -%}
        {%-     when Some(throwable) -%}
        throws {{ throwable|type_name(ci, config) }}
        {%-     else -%}
        {%- endmatch %} {
            try {
                {% match callable.return_type() -%}
                {%- when Some with (return_type) -%}
                {%- if return_type|has_primitive_ffi_type -%}
                return {% call to_ffi_call(callable) %}{% endcall %}
                {%- else -%}
                return {{ return_type|lift_fn(config, ci) }}({% call to_ffi_call(callable) %}{% endcall %})
                {%- endif -%}
                {%- when None %}{% call to_ffi_call(callable) %}{% endcall %}{%- endmatch %};
            } catch (java.lang.RuntimeException _uniffi_ex) {
                {% match callable.throws_type() %}
                {% when Some(throwable) %}
                if ({{ throwable|type_name(ci, config) }}.class.isInstance(_uniffi_ex.getCause())) {
                    throw ({{ throwable|type_name(ci, config) }})_uniffi_ex.getCause();
                }
                {% else %}
                {% endmatch %}
                if (InternalException.class.isInstance(_uniffi_ex.getCause())) {
                    throw (InternalException)_uniffi_ex.getCause();
                }
                throw _uniffi_ex;
            }
    }
    {% endif %}
{% endmacro %}

{%- macro call_async(callable) -%}
    UniffiAsyncHelpers.uniffiRustCallAsync(
        _uniffiExecutor,
{%- match callable.self_type() %}
{%- when Some with (Type::Object { .. }) %}
        callWithHandle(_uniffiHandle -> {
            return UniffiLib.{{ callable.ffi_func().name() }}(
                _uniffiHandle{% if callable.arguments().len() != 0 %},{% endif %}
                {% call arg_list_lowered(callable) %}{% endcall %}
            );
        }),
{%- when Some(t) %}
        UniffiLib.{{ callable.ffi_func().name() }}(
            {{ t|lower_fn(config, ci) }}(this){% if callable.arguments().len() != 0 %},{% endif %}
            {% call arg_list_lowered(callable) %}{% endcall %}
        ),
{%- when None %}
        UniffiLib.{{ callable.ffi_func().name() }}({% call arg_list_lowered(callable) %}{% endcall %}),
{%- endmatch %}
        {{ callable|async_poll(ci) }},
        {{ callable|async_complete(ci, config) }},
        {{ callable|async_cancel(ci) }},
        {{ callable|async_free(ci) }},
        // lift function
        {%- match callable.return_type() %}
        {%- when Some(return_type) %}
        (_uniffiResult) -> {{ return_type|lift_fn(config, ci) }}(_uniffiResult),
        {%- when None %}
        () -> {},
        {%- endmatch %}
        // Error FFI converter
        {%- match callable.throws_type() %}
        {%- when Some(e) %}
        {%- if e|is_external(ci) %}
        new {{ e|class_name_from_type(ci) }}ExternalErrorHandler()
        {%- else %}
        new {{ e|type_name(ci, config) }}ErrorHandler()
        {%- endif %}
        {%- when None %}
        new UniffiNullRustCallStatusErrorHandler()
        {%- endmatch %}
    )
{%- endmacro %}

{%- macro arg_list_lowered(func) %}
    {%- for arg in func.arguments() %}
        {%- if arg|has_primitive_ffi_type -%}
        {{- arg.name()|var_name }}
        {%- else -%}
        {{- arg|lower_fn_for_arg(config, ci) }}({{ arg.name()|var_name }})
        {%- endif -%}
    {%- if !loop.last %}, {% endif -%}
    {%- endfor %}
{%- endmacro -%}

{#-
// Arglist of just argument names, for forwarding calls (e.g. delegation between overloads).
-#}
{%- macro arg_name_list(func) -%}
{%- for arg in func.arguments() -%}
    {{ arg.name()|var_name }}
{%-     if !loop.last %}, {% endif -%}
{%- endfor %}
{%- endmacro -%}

{#-
// Arglist as used in Java declarations of methods, functions and constructors.
// even if `is_decl` there won't be default values, Java doesn't support them in any reasonable way.
// Note the var_name and type_name filters.
-#}

{#- Declaration side of a call into Rust, so zero-copy `&[u8]` shows as a ByteBuffer. -#}
{% macro arg_list(func, is_decl) %}
{%- for arg in func.arguments() -%}
        {{ arg|lower_type_name_for_arg(ci, config) }} {{ arg.name()|var_name }}
{%-     if !loop.last %}, {% endif -%}
{%- endfor %}
{%- endmacro %}

{% macro field_name(field, field_num) %}
{{- field|field_java_name(field_num) -}}
{%- endmacro %}

{% macro field_name_unquoted(field, field_num) %}
{%- if field.name().is_empty() -%}
v{{- field_num -}}
{%- else -%}
{{ field.name()|var_name|unquote }}
{%- endif -%}
{%- endmacro %}

// Macro for destroying fields
{%- macro destroy_fields(member) %}
    AutoCloseableHelper.close(
    {%- for field in member.fields() %}
        this.{% call field_name(field, loop.index) %}{% endcall %}{%- if !loop.last %}, {% endif -%}
    {% endfor -%});
{%- endmacro -%}

{%- macro docstring_value(maybe_docstring, indent_spaces) %}
{%- match maybe_docstring %}
{%- when Some(docstring) %}
{{ docstring|docstring(indent_spaces) }}
{%- else %}
{%- endmatch %}
{%- endmacro %}

{%- macro docstring(defn, indent_spaces) %}
{%- call docstring_value(defn.docstring(), indent_spaces) %}{% endcall %}
{%- endmacro %}

{# Macro for uniffi_trait implementations - Display, Eq, Hash, Ord #}
{%- macro uniffi_trait_impls(uniffi_trait_methods) %}
{# Prefer Display, fall back to Debug #}
{%- if let Some(fmt) = uniffi_trait_methods.display_fmt.or(uniffi_trait_methods.debug_fmt.clone()) %}
    @Override
    public java.lang.String toString() {
        return {{ fmt.return_type().unwrap()|lift_fn(config, ci) }}({% call to_ffi_call(fmt) %}{% endcall %});
    }
{%- endif %}
{%- if let Some(eq) = uniffi_trait_methods.eq_eq %}
    @Override
    public boolean equals(java.lang.Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof {{ eq.object_name()|class_name(ci) }})) return false;
        {{ eq.object_name()|class_name(ci) }} other = ({{ eq.object_name()|class_name(ci) }}) obj;
        return {{ eq.return_type().unwrap()|lift_fn(config, ci) }}({% call to_ffi_call(eq) %}{% endcall %});
    }
{%- endif %}
{%- if let Some(hash) = uniffi_trait_methods.hash_hash %}
    @Override
    public int hashCode() {
        return {{ hash.return_type().unwrap()|lift_fn(config, ci) }}({%- call to_ffi_call(hash) %}{% endcall %}).intValue();
    }
{%- endif %}
{%- if let Some(cmp) = uniffi_trait_methods.ord_cmp %}
    @Override
    public int compareTo({{ cmp.object_name()|class_name(ci) }} other) {
        if (other == null) throw new java.lang.NullPointerException();
        return {{ cmp.return_type().unwrap()|lift_fn(config, ci) }}({%- call to_ffi_call(cmp) %}{% endcall %}).intValue();
    }
{%- endif %}
{%- endmacro %}

{# Macro for uniffi_trait implementations as default interface methods (for sealed interfaces) #}
{%- macro uniffi_trait_impls_interface(uniffi_trait_methods) %}
{# Prefer Display, fall back to Debug #}
{%- if let Some(fmt) = uniffi_trait_methods.display_fmt.or(uniffi_trait_methods.debug_fmt.clone()) %}
    default java.lang.String toStringTrait() {
        return {{ fmt.return_type().unwrap()|lift_fn(config, ci) }}({% call to_ffi_call(fmt) %}{% endcall %});
    }
{%- endif %}
{%- if let Some(eq) = uniffi_trait_methods.eq_eq %}
    default boolean equalsTrait(java.lang.Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof {{ eq.object_name()|class_name(ci) }})) return false;
        {{ eq.object_name()|class_name(ci) }} other = ({{ eq.object_name()|class_name(ci) }}) obj;
        return {{ eq.return_type().unwrap()|lift_fn(config, ci) }}({% call to_ffi_call(eq) %}{% endcall %});
    }
{%- endif %}
{%- if let Some(hash) = uniffi_trait_methods.hash_hash %}
    default int hashCodeTrait() {
        return {{ hash.return_type().unwrap()|lift_fn(config, ci) }}({%- call to_ffi_call(hash) %}{% endcall %}).intValue();
    }
{%- endif %}
{%- if let Some(cmp) = uniffi_trait_methods.ord_cmp %}
    default int compareTo({{ cmp.object_name()|class_name(ci) }} other) {
        if (other == null) throw new java.lang.NullPointerException();
        return {{ cmp.return_type().unwrap()|lift_fn(config, ci) }}({%- call to_ffi_call(cmp) %}{% endcall %}).intValue();
    }
{%- endif %}
{%- endmacro %}
