{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% load custom_filters %}

{% block headtitle %}Add new media - {{PORTAL_NAME}}{% endblock headtitle %}

{% block externallinks %}
{% if LOAD_FROM_CDN %}
<link href="https://cdnjs.cloudflare.com/ajax/libs/file-uploader/5.13.0/fine-uploader.min.js" rel="preload" as="script">
<script src="https://cdnjs.cloudflare.com/ajax/libs/file-uploader/5.13.0/fine-uploader.min.js"></script>
{% else %}
<link href="{% static "lib/file-uploader/5.13.0/fine-uploader.min.js" %}" rel="preload" as="script">
<script src="{% static "lib/file-uploader/5.13.0/fine-uploader.min.js" %}"></script>
{% endif %}
{% endblock externallinks %}

{% block topimports %}
<link href="{% static "css/add-media.css" %}" rel="preload" as="style">
<link href="{% static "css/add-media.css" %}" rel="stylesheet">
<style>
    /* LMS Embed Mode specific styling */
    body.lms-embed-mode {
        overflow-y: hidden;
    }
    .media-uploader-wrap.is-lms-embed {
        max-width: 680px;
        padding: 10px 15px;
    }
    .media-uploader-wrap.is-lms-embed .media-uploader {
        width: 50%;
        margin: 0 auto;
    }
    .is-lms-embed .media-uploader-top-wrap {
        margin-bottom: 10px;
        padding: 0;
    }
    .is-lms-embed .media-uploader-top-left-wrap h1 {
        display: none;
    }
    .is-lms-embed .media-uploader-bottom-wrap {
        margin-top: 10px;
    }
    .is-lms-embed .media-drag-drop-inner {
        padding: 20px 10px;
        min-height: 140px;
        border-width: 2px;
    }
    .is-lms-embed .media-drag-drop-content-inner span {
        font-size: 13px;
        margin-bottom: 6px;
        line-height: 1.2;
    }
    .is-lms-embed .media-drag-drop-content-inner i.material-icons {
        font-size: 32px;
        margin-bottom: 4px;
    }
    .is-lms-embed .qq-upload-button-selector {
        padding: 6px 16px;
        font-size: 13px;
        margin-top: 5px;
    }
    .is-lms-embed .media-upload-items-list {
        margin-top: 10px;
    }
</style>
{% endblock topimports %}

{% block innercontent %}
{% get_current_language as LANGUAGE_CODE %}

{% if request.user.is_authenticated %}

    {% if can_add %}

        <div class="media-uploader-wrap" id="media-uploader-wrap">
            <div class="media-uploader-top-wrap">
                <div class="media-uploader-top-left-wrap">
                    <h1>{{ "Upload media" | custom_translate:LANGUAGE_CODE}}</h1>
                </div>
                <div class="media-uploader-top-right-wrap"> </div>
            </div>

            <script type="text/template" id="qq-template">
                <div class="media-uploader-bottom-wrap qq-uploader-selector">
                    <div class="media-uploader-bottom-left-wrap">
                        <div class="media-drag-drop-wrap">
                            <div class="media-drag-drop-inner" qq-drop-area-text="Drop files here">
                                <div class="media-drag-drop-content">
                                    <div class="media-drag-drop-content-inner">
                                        <span><i class="material-icons">cloud_upload</i></span>
                                        <span>{{ "Drag and drop files" | custom_translate:LANGUAGE_CODE}}</span>
                                        <span>{{ "or" | custom_translate:LANGUAGE_CODE}}</span>
                                        <span class="browse-files-btn-wrap">
                                            <span class="qq-upload-button-selector">{{ "Browse your files" | custom_translate:LANGUAGE_CODE}}</span>
                                        </span>

                                        <div class="qq-upload-drop-area-selector media-dropzone" qq-hide-dropzone>
                                            <span class="qq-upload-drop-area-text-selector"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="media-uploader-bottom-right-wrap">
                        <ul class="media-upload-items-list qq-upload-list-selector">
                            <li>
                                <div class="media-upload-item-main">
                                    <div class="media-upload-item-thumb">
                                        <img class="qq-thumbnail-selector" qq-max-size="120" qq-server-scale alt="" />
                                        <span class="media-upload-item-spinner qq-upload-spinner-selector"><i class="material-icons">autorenew</i></span>
                                        <button type="button" class="qq-upload-retry-selector retry-media-upload-item" aria-label="Retry"><i class="material-icons">refresh</i> Retry</button>
                                    </div>
                                    <div class="media-upload-item-details">
                                        <div class="media-upload-item-name">
                                            <span class="media-upload-item-filename qq-upload-file-selector"></span>
                                            <input class="media-upload-item-filename-input qq-edit-filename-selector" tab-index="0" type="text" />
                                        </div>
                                        <div class="media-upload-item-details-bottom">
                                            <div class="media-upload-item-progress-bar-container qq-progress-bar-container-selector">
                                                <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="media-upload-item-progress-bar qq-progress-bar-selector"></div>
                                            </div>
                                            <span class="media-upload-item-upload-size qq-upload-size-selector"></span>
                                            <span role="status" class="media-upload-item-status-text qq-upload-status-text-selector"></span>
                                        </div>
                                        <div class="media-upload-item-top-actions">
                                            <span class="filename-edit qq-edit-filename-icon-selector" aria-label="Edit filename">Edit filename <i class="material-icons">create</i></span>
                                            <button type="button" class="delete-media-upload-item qq-upload-delete-selector" aria-label="Delete">Delete <i class="material-icons">delete</i></button>
                                            <button type="button" class="cancel-media-upload-item qq-upload-cancel-selector" aria-label="Cancel">Cancel <i class="material-icons">cancel</i></button>
                                            <a href="#" class="view-uploaded-media-link qq-hide">{{ "View media" | custom_translate:LANGUAGE_CODE}}<i class="material-icons">open_in_new</i></a>
                                        </div>
                                        <div class="media-upload-item-bottom-actions">
                                            <button type="button" class="continue-media-upload-item qq-upload-continue-selector" aria-label="Continue"><i class="material-icons">play_circle_outline</i> Continue</button>
                                            <button type="button" class="pause-media-upload-item qq-upload-pause-selector" aria-label="Pause"><i class="material-icons">pause_circle_outline</i> Pause</button>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        </ul>
                        <dialog class="qq-alert-dialog-selector">
                            <div class="qq-dialog-message-selector"></div>
                            <div class="qq-dialog-buttons">
                                <button type="button" class="qq-cancel-button-selector">CLOSE</button>
                            </div>
                        </dialog>
                        <dialog class="qq-confirm-dialog-selector">
                            <div class="qq-dialog-message-selector"></div>
                            <div class="qq-dialog-buttons">
                                <button type="button" class="qq-cancel-button-selector">NO</button>
                                <button type="button" class="qq-ok-button-selector">YES</button>
                            </div>
                        </dialog>
                        <dialog class="qq-prompt-dialog-selector">
                            <div class="qq-dialog-message-selector"></div>
                            <input type="text">
                            <div class="qq-dialog-buttons">
                                <button type="button" class="qq-cancel-button-selector">CANCEL</button>
                                <button type="button" class="qq-ok-button-selector">OK</button>
                            </div>
                        </dialog>
                    </div>
                </div>
            </script>
            <div class="media-uploader"></div>
        </div>

    {% else %}

        {{can_upload_exp}}

        <br>

        <a href='/contact'>Contact</a> portal owners for more information.

    {% endif %}

{% endif %}
{% endblock innercontent %}

{% block bottomimports %}
<script src="{% static "js/add-media.js" %}?v={{ VERSION }}"></script>
<script>
    document.addEventListener("DOMContentLoaded", function(event) {

        var urlParams = new URLSearchParams(window.location.search);
        var isLmsEmbedMode = sessionStorage.getItem('lms_embed_mode') === 'true' && urlParams.get('action') === 'select_media';

        // Add compact styles if in LMS embed mode
        if (isLmsEmbedMode) {
            var wrap = document.getElementById('media-uploader-wrap');
            if (wrap) {
                wrap.classList.add('is-lms-embed');
            }
            document.body.classList.add('lms-embed-mode');
        }

        function getCSRFToken() {
            var i, cookies, cookie, cookieVal = null;
            if ( document.cookie && '' !== document.cookie ) {
                cookies = document.cookie.split(';');
                i = 0;
                while( i < cookies.length ){
                    cookie = cookies[i].trim();
                    if ( 'csrftoken=' === cookie.substring(0, 10) ) {
                        cookieVal = decodeURIComponent( cookie.substring(10) );
                        break;
                    }
                    i += 1;
                }
            }
            return cookieVal;
        }

        var default_concurrent_chunked_uploader = new qq.FineUploader({
            debug: true,
            element: document.querySelector('.media-uploader'),
            request: {
                endpoint: '{% url 'uploader:upload' %}',
                params: {},
                customHeaders: {
                    'X-CSRFToken': getCSRFToken('csrftoken'),
                },
            },
            retry: {
                enableAuto: true,
                maxAutoAttempts: 2,
            },
            validation: {
                itemLimit: isLmsEmbedMode ? 1 : {{UPLOAD_MAX_FILES_NUMBER}},
                sizeLimit: {{UPLOAD_MAX_SIZE}},
            },
            chunking: {
                enabled: true,
                concurrent: {
                    enabled: true,
                },
                success: {
                    endpoint: '{% url 'uploader:upload' %}?done',
                },
            },
            callbacks: {
                onError: function(id, name, errorReason, xhrOrXdr) {
                    console.warn(qq.format("Error on file number {} - {}.  Reason: {}", id, name, errorReason));
                },
                onComplete: function( id, name, response, request ) {

                    if ( response.success ) {

                        if ( response.media_url ) {
                            if ( 1 === this._currentItemLimit ) {
                                if (isLmsEmbedMode && window.parent !== window) {
                                    var mediaUrl = response.media_url;
                                    var mediaId = '';
                                    if (mediaUrl.indexOf('m=') > -1) {
                                        mediaId = mediaUrl.split('m=')[1].split('&')[0];
                                    } else {
                                        var parts = mediaUrl.split('/').filter(Boolean);
                                        mediaId = parts[parts.length - 1];
                                    }
                                    var baseUrl = window.location.origin;
                                    var embedUrl = baseUrl + '/embed?m=' + mediaId;

                                    var sendPostMsg = function() {
                                        window.parent.postMessage({
                                            type: 'videoSelected',
                                            embedUrl: embedUrl,
                                            videoId: mediaId
                                        }, '*');
                                    };

                                    sendPostMsg();
                                    return;
                                }
                                setTimeout(function(){ window.location.href = response.media_url; }, 500);
                                return;
                            }
                        }

                        var listEl = document.querySelector( '.qq-file-id-' + id );
                        var viewFileEl = listEl.querySelector( '.view-uploaded-media-link' );

                        if ( listEl ) {
                            var fileUrl = response.media_url;
                            listEl.style.cursor = 'pointer';
                            listEl.addEventListener( 'click', function(ev) {
                                ev.preventDefault();
                                ev.stopPropagation();
                                window.location.href = fileUrl;
                            });
                        }

                        if ( viewFileEl ) {
                            viewFileEl.setAttribute( 'href', response.media_url );
                            viewFileEl.setAttribute( 'class', 'view-uploaded-media-link' );
                        }
                    }
                },
            },
        });
    });
</script>
{% endblock bottomimports %}
