{% load i18n %}

<div class="modal" tabindex="-1" role="dialog" id="modal_recipe">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{% trans 'Recipe' %}</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" style="text-align: center">
                <i class="fas fa-spinner fa-spin fa-8x" id="id_spinner"></i>
                <a href="" id="a_recipe_open" target="_blank" onclick="afterClick()" style="font-size: 250%"></a>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">{% trans 'Close' %}</button>
            </div>
        </div>
    </div>
</div>

<script type="application/javascript">
    function openRecipe(id) {
        var link = $('#a_recipe_open');
        link.hide();
        $('#id_spinner').show();

        var url = "{% url 'api_get_external_file_link' recipe_id=12345 %}".replace(/12345/, id);

        link.text("{% trans 'Open Recipe' %}");
        $('#modal_recipe').modal('show');

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
                    link.attr("href", this.responseText);
                    link.show();
                } else {
                    window.open(this.responseText);
                    $('#modal_recipe').modal('hide');
                }

                $('#id_spinner').hide();

            }
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    }

    function afterClick() {
        $('#modal_recipe').modal('hide');
        return true;
    }
</script>