{# -*- mode: jinja-html -*- #}
{% extends 'base.j2' %}
{% import 'bootstrap/wtf.html' as wtf %}

{% block styles %}
{{super()}}
{% endblock %}

{% block app_content %}
<h1>{{ title }}</h1>
<br>
<div class="row">
    <div class="col-md-4">
        <p>
            (*) champs requis
        </p>
        {{ wtf.quick_form(form, novalidate=True) }}
    </div>

    <div id="sirene-data" class="col-md-5">
        <b>Informations de la base SIRENE</b>
        <div id="nom_entreprise_base"></div>
        <div id="adresse_base"></div>
        <div id="codepostal_base"></div>
        <div id="ville_base"></div>
        <a class="btn btn-primary" onclick="getData()">Copier</a>
    </div>
</div>

<script>
    var value = document.getElementById("siret").value;
    fetch("https://entreprise.data.gouv.fr/api/sirene/v1/siret/" + value)
        .then(response => {
            if (response.ok)
                return response.json()
        })
        .then(response => showSireneData(response))
        .catch(err => {
            document.getElementById("sirene-data").style.display = "none"
            return err
        })

    function showSireneData(response) {
        document.getElementById("nom_entreprise_base").innerHTML = "Nom de l'entreprise: " + response.etablissement.l1_normalisee
        document.getElementById("adresse_base").innerHTML = "Adresse: " + response.etablissement.l4_normalisee
        document.getElementById("codepostal_base").innerHTML = "Code postal: " + response.etablissement.code_postal
        document.getElementById("ville_base").innerHTML = "Ville: " + response.etablissement.libelle_commune
    }

    function getData() {
        var value = document.getElementById("siret").value;
        fetch("https://entreprise.data.gouv.fr/api/sirene/v1/siret/" + value)
            .then(response => {
                if (response.ok)
                    return response.json()
            })
            .then(response => fillForm(response))
            .catch(err => err)
    }

    function fillForm(response) {
        document.getElementById("nom").value = response.etablissement.l1_normalisee
        document.getElementById("adresse").value = response.etablissement.l4_normalisee
        document.getElementById("codepostal").value = response.etablissement.code_postal
        document.getElementById("ville").value = response.etablissement.libelle_commune
    }
</script>
{% endblock %}