{% macro form(model, bfms, name) -%}
<div class="row mb-3">
    <form>
        {% block modal_content %}
        {% endblock %}
        {% for key, field in fields.items() %}
            {% if not field.auto %}
                <div class="col-lg-12 mb-3">
                    <label class="form-label">{{ key.replace('_', ' ').title() }}</label>
                    {% with value=bfms[obj.__getattribute__(key).remote_model] if obj and field.get('source_field') else (obj.__getattribute__(key) if obj else field['default']) %}
                        {% include "components/inputs/"+field.input+".html" %}
                    {% endwith %}
                </div>
            {% endif %}
        {% endfor %}
        <button class="btn btn-primary ms-auto" {{ '' if obj else 'data-bs-dismiss=modal' }} type="submit">
            {{ 'Edit' if obj else 'New' }} {{ name }}
        </button>
        {% if obj %}
        <button class="btn btn-danger ms-auto" {{ '' if obj else 'data-bs-dismiss=modal' }} type="button" onclick="del()">
            Delete
        </button>
        {% endif %}
    </form>
</div>

<script>
{# form submit #}
document.getElementsByTagName('form')[0].onsubmit = async e => {
    e.preventDefault()
    var fd = new FormData(e.target)
    const data = Object.fromEntries(fd)
    fd.keys().forEach(k => {
        if (e.target[k].dataset?.type=='json') {data[k] = JSON.parse(data[k].replace(/'/g, '"'))}
        else if (k.endsWith('[]')) {data[k.replace('[]', '')] = fd.getAll(k).map(i => Number(i)); delete data[k]}
        else if (parseFloat(data[k])==data[k]) {data[k] = Number(data[k])}
    })
    await fetch("/v2/{{ name }}{{ obj and '/'+(obj.pk | string) }}", {
        method: "{{ 'PATCH' if obj else 'PUT' }}",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer {{ request.cookies["token"] }}'
        },
        body: JSON.stringify(data)
    })
    {% if obj %}
    window.location = '/{{ name }}'
    {% else %}
    $('#dt-{{ name }}').DataTable().ajax.reload()
    {% endif %}
}
{# delete button #}
{% if obj %}
const del = async e => {
    await fetch("/v2/{{ name }}/{{ obj.pk | string }}", {
        method: 'DELETE',
        headers: {
            'Authorization': 'Bearer {{ request.cookies["token"] }}'
        },
    })
    window.location = '/{{ name }}'
}
{% endif %}

</script>
{%- endmacro %}