{% extends "base.html" %}

{% block title %}
Create server
{% endblock title %}

{% block content %}
<div class="mb-10">
    <form hx-post="/servers" hx-ext="submitjson">
        <h1>Create new server</h1>
        <div class="mb-5">
        <div>
        <label>name</label>
        <br />
        <input id="name" name="name" type="text" value=""/>
        </div>
    <div>
        <label>domain</label>
        <br />
        <input id="domain" name="domain" type="text" value=""/>
        </div>
    </div>
    <div>
        <button class=" text-xs py-3 px-6 rounded-lg bg-gray-900 text-white" type="submit">Submit</button>
    </div>
    </form>
</div>
{% endblock content %}

{% block js %}
<script>
    htmx.defineExtension('submitjson', {
        onEvent: function (name, evt) {
            if (name === "htmx:configRequest") {
                evt.detail.headers['Content-Type'] = "application/json"
            }
        },
        encodeParameters: function (xhr, parameters, elt) {
            const json = {};
            for (const [key, value] of Object.entries(parameters)) {
                const inputType = elt.querySelector(`[name=${key}]`).type;
                if (inputType === 'number') {
                    json[key] = parseFloat(value);
                } else if (inputType === 'checkbox') {
                    json[key] = elt.querySelector(`[name=${key}]`).checked;
                } else {
                    json[key] = value;
                }
            }
            return JSON.stringify(json);
        }
    })
</script>
{% endblock js %}