let maybe_fn = self.inner.dollar("{{ method_name }}");
let fn_robj = match maybe_fn {
    Ok(v) if !v.is_null() && !v.is_na() => v,
{% if has_error %}
    _ => return Err({{ core_import }}::KreuzbergError::Plugin {
        message: format!("Plugin '{}' missing method '{{ method_name }}'", self.cached_name),
        plugin_name: self.cached_name.clone(),
    }),
{% else %}
    _ => return Default::default(),
{% endif %}
};

{% if empty_args %}
let result = fn_robj.call(extendr_api::Pairlist::new());
{% else %}
let args = extendr_api::Pairlist::from_pairs(&[{{ args_pairs }}]);
let result = fn_robj.call(args);
{% endif %}

{% if has_error %}
match result {
    Err(_) => Err({{ core_import }}::KreuzbergError::Plugin {
        message: format!("Plugin '{}' method '{{ method_name }}' failed", self.cached_name),
        plugin_name: self.cached_name.clone(),
    }),
    Ok(val) => {
        let s = val.as_string().ok().and_then(|mut v| {
            if v.is_empty() { None } else { Some(v.remove(0)) }
        }).unwrap_or_default();

        match s.as_str() {
            "" | "null" => Ok(Default::default()),
            _ => serde_json::from_str::<_>(&s).map_err(|e| {{ core_import }}::KreuzbergError::Plugin {
                message: format!("Failed to parse return value: {}", e),
                plugin_name: self.cached_name.clone(),
            })
        }
    }
}
{% else %}
match result {
    Err(_) => Default::default(),
    Ok(val) => {
        let s = val.as_string().ok().and_then(|mut v| {
            if v.is_empty() { None } else { Some(v.remove(0)) }
        }).unwrap_or_default();

        match s.as_str() {
            "" | "null" => Default::default(),
            _ => serde_json::from_str::<_>(&s).unwrap_or_default()
        }
    }
}
{% endif %}
