{% load i18n %}
$(function() {
    var commit_id = '{{ current_commit.id }}' || '{{ repo.head_cmmt_id }}';
    function load_excel() {
        $('#file-view').css({'height': 'auto'}).find('.loading-tip').hide();
        var iframe = document.createElement('iframe');
        iframe.src = '{{ SITE_ROOT}}office-convert/static/{{ repo.id }}/' + commit_id + '{{ path|urlencode }}/index.html?token=' + '{{ shared_token }}';
        $('#spreadsheet-container').append(iframe);
        iframe.onload = function () {
            this.height = this.contentDocument.body.scrollHeight;
        };
    }

    function check_status () {
        var url = "{% url 'office_convert_query_status' %}?" + $.param({
            repo_id: '{{ repo.id }}',
            path: '{{ path|escapejs }}',
            token: '{{ shared_token }}',
            commit_id: commit_id,
            doctype: 'spreadsheet'
        });
        $.ajax({
            url: url,
            cache: false,
            dataType: 'json',
            success: function(data) {
                var status = data['status'];
                if (status == 'QUEUED' || status == 'PROCESSING') {
                    setTimeout(check_status, 2000);
                } else {
                    load_excel();
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                var str;
                if (xhr.responseText) {
                    str = "{% trans "Document convertion failed." %}";
                } else {
                    str = "{% trans "Failed. Please check the network." %}";
                }
                $('#file-view').html('<div id="file-view-tip"><p class="error">' + str + '</p></div>');
            }
        });
    }

    check_status();
});
