{% load seahub_tags avatar_tags i18n static %}

<!DOCTYPE html>
<html>
<head>
<title>{{doc_title}}</title>
{% if request.is_mobile or request.is_tablet %}
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
{% else %}
<meta name="viewport" content="width=device-width, initial-scale=1" />
{% endif %}
<link rel="icon" href="{{ MEDIA_URL }}{{ favicon_path }}" />
<style type="text/css">
html, body { padding:0; margin:0; height:100%; }
</style>
</head>

<body>

<div id="placeholder"></div>

{% get_current_language as LANGUAGE_CODE %}
<script type="text/javascript" src="{% static "scripts/lib/jquery.min.js" %}"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}js/base.js?t=1536127546642"></script>
<script type="text/javascript" src="{{ ONLYOFFICE_APIJS_URL }}"></script>
<script type="text/javascript">
    {% if onlyoffice_jwt_token %}
    var onRequestHistory = function() {
        $.ajax({
            url: '{% url "api-v2.1-new-file-history-view" repo_id %}' + '?path={{path|urlencode}}',
            type: 'GET',
            dataType: 'json',
            cache: false,
            success: function(resp) {
                var history = [];
                resp.data.reverse().forEach (function (item) {
                    history.push({
                        "created": item.ctime,
                        "key": item.rev_file_id,
                        "user": {
                            "id": item.creator_email,
                            "name": item.creator_name
                        },
                        "version": item.rev_file_id
                    });
                });
                docEditor.refreshHistory({
                    "currentVersion": history.at(-1).version,
                    "history": history
                });
            }
        });
    };
    var onRequestHistoryData = function(event) {
        var version = event.data;
        var data = {
            "repo_id": "{{repo_id}}",
            "file_path": "{{path}}",
            "obj_id": version
        };

        $.ajax({
            url: '{% url "onlyoffice_api_get_history_file_access_token" %}',
            type: 'POST',
            dataType: 'json',
            cache: false,
            beforeSend: prepareCSRFToken,
            data: data,
            success: function(resp) {
                docEditor.setHistoryData(resp.data);
            }
        });
    };
    var onRequestHistoryClose = function () {
        document.location.reload();
    };

    var onRequestReferenceData = function (event) {
        $.ajax({
            url: '{% url "onlyoffice_api_get_reference_data" %}',
            type: 'POST',
            dataType: 'json',
            cache: false,
            data: event.data.referenceData,
            beforeSend: prepareCSRFToken,
            success: function(resp) {
                docEditor.setReferenceData(resp.data);
            },
            error: function(xhr, status, error) {
                if (xhr.responseText) {
                    errMsg = JSON.parse(xhr.responseText).error_msg;
                } else {
                    errMsg = "{% trans "Failed. Please check the network." %}";
                }
                docEditor.setReferenceData({
                    "error": errMsg
                })
            }
        });
    };
    {% endif %}
    var config = {
        {% if onlyoffice_jwt_token %}
        "events": {
            "onRequestReferenceData": onRequestReferenceData,
            "onRequestHistory": onRequestHistory,
            "onRequestHistoryData": onRequestHistoryData,
            "onRequestHistoryClose": onRequestHistoryClose,
        },
        {% endif %}
        "type": window.screen.width < 992 ? 'mobile' : 'desktop',
        "document": {
            "fileType": "{{ file_type }}",
            "key": "{{ doc_key }}",
            "title": "{{ doc_title|escapejs }}",
            "url": "{{ doc_url }}",
            "permissions": {
                "download": {% if can_download %}true{% else %}false{% endif %},
                "edit": {% if can_edit %}true{% else %}false{% endif %},
                "copy": {% if can_copy %}true{% else %}false{% endif %},
                "print": {% if can_download %}true{% else %}false{% endif %},
                "review": true
            },
            "referenceData": {
                "fileKey": '{{ file_key }}',
                "instanceId": "{{ instance_id }}",
            },
        },
        "documentType": "{{ document_type }}", // 'text' | 'spreadsheet' | 'presentation',
        {% if onlyoffice_jwt_token %}
        "token": "{{ onlyoffice_jwt_token }}",
        {% endif %}
        "editorConfig": {
            "callbackUrl": "{{ callback_url }}",
            "lang": "{{ LANGUAGE_CODE }}",
            "mode": {% if can_edit %}"edit"{% else %}"view"{% endif %},
            "customization": {
                "forcesave": {% if onlyoffice_force_save %}true{% else %}false{% endif %},
                {% if not request.user.is_authenticated %}
                "anonymous": {
                    "request": true,
                    "label": "Guest"
                },
                {% endif %}
            },
            {% if request.user.is_authenticated %}
            "user": {
                "id": "{{ username|escapejs }}",
                "name": "{{ username|email2nickname|escapejs }}",
                "image": "{{ avatar_url }}",
            }
            {% endif %}
        }
    };
    var docEditor = new DocsAPI.DocEditor("placeholder", config);
</script>
<script type="text/javascript">
    var SEAFILE_GLOBAL = {
        csrfCookieName: '{{ CSRF_COOKIE_NAME }}'
    };

    {% if can_edit %}
    var interval;
    {% if not share_link_token %}
    var refreshLock = function() {
        $.ajax({
            url: '{% url "api-v2.1-file-view" repo_id %}' + '?p={{path|urlencode}}',
            type: 'PUT',
            dataType: 'json',
            data: {
                'operation': 'refresh-lock',
                'expire': 2400
            },
            cache: false,
            beforeSend: prepareCSRFToken,
            success: function(data) {
            },
            error: function(xhr) {
                if (xhr.responseText) {
                    feedback(JSON.parse(xhr.responseText).error_msg, 'error');
                } else {
                    feedback("{% trans "Failed. Please check the network." %}", 'error');
                }
                clearInterval(interval);
            }
        });
    };
    {% else %}
    var refreshLock = function() {
        $.ajax({
            url: '{% url "api-v2.1-share-link-online-office-lock" share_link_token %}',
            type: 'PUT',
            dataType: 'json',
            data: {
                'expire': 2400
            },
            cache: false,
            beforeSend: prepareCSRFToken,
            success: function(data) {
            },
            error: function(xhr) {
                if (xhr.responseText) {
                    feedback(JSON.parse(xhr.responseText).error_msg, 'error');
                } else {
                    feedback("{% trans "Failed. Please check the network." %}", 'error');
                }
                clearInterval(interval);
            }
        });
    };
    {% endif %}
    interval = setInterval(refreshLock, 40 * 60 * 1000);
    {% endif %}
</script>
{% if request_from_onlyoffice_desktop_editor %}
<script type="text/javascript">
    var params = {
      "displayName": "{{request.user.username|email2nickname|escapejs}}",
      "email": "{{request.user.username|escapejs}}",
      "domain": "{{service_url}}",
      "provider": "seafile",
      "userId": "{{request.user.username|escapejs}}",
    };
    window.AscDesktopEditor.execCommand('portal:login', JSON.stringify(params));
</script>
{% endif %}
{% if enable_watermark %}
<script type="text/javascript" src="{{ MEDIA_URL }}js/watermark.js"></script>
<script type="text/javascript">{% include "snippets/add_watermark.html" %}</script>
{% endif %}
</body>
</html>
