{% extends "setup/setup_page.jinja" %}

{% block setup %}
    <h1>{{ _("Setup Tor daemon") }}</h1>
    <div class="flex mt-5">
        <img src="{{ url_for('static', filename='img/favicon-dark-mode.png') }}" style="width: 32px;"/> 
        <img src="{{ url_for('static', filename='img/arrow-right.svg') }}" style="width: 32px;" class="svg-white"/>
        <img style="width: 32px;" src="{{ url_for('static', filename='img/tor.svg') }}"/>
    </div>
    <div class="grid grid-cols-2 gap-3 mt-8">
        {% if nextURL == 'setup_endpoint.node_type'%}
            <a href="{{ url_for('setup_endpoint.node_type') }}" class="button">{{ _("Skip") }}</a>
        {% endif %}
        <button type="button" class="button bg-accent" id="setup-tor-button" onclick="setupTorDaemon()">{{ _("Setup Tor") }}</button>
    </div>
{% endblock %}

{% block setup_scripts %}
    <script>
        async function setupTorDaemon() {
            let url = "{{ url_for('setup_endpoint.setup_tor') }}";
            var formData = new FormData();
            formData.append('csrf_token', '{{ csrf_token() }}');
            try {
                const response = await fetch(
                    url,
                    {
                        method: 'POST',
                        body: formData
                    }
                );
                if(response.status != 200){
                    showError(await response.text());
                    return;
                }
                const jsonResponse = await response.json();
                if ("success" in jsonResponse) {
                    document.getElementById('setup-tor-button').classList.add('hidden');
                    showPacman()
                    startProgressCheck('torbrowser', "{{ url_for(nextURL) }}");
                    return;
                } if (jsonResponse.error == "Tor is already installed") {
                    window.location.href = "{{ url_for(nextURL) }}";
                }
                showError(jsonResponse.error, 4000);
            }  catch(e) {
                showError(`{{ _("Failed to install Tor daemon...") }}`);
                showError(e);
            }
        }
    </script>
{% endblock %}
