<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/** @var $block \Magento\Cms\Block\Adminhtml\Wysiwyg\Images\Content\Uploader */
?>

<div id="<?= $block->getHtmlId() ?>" class="uploader">
    <span class="fileinput-button form-buttons">
        <span><?= $block->escapeHtml(__('Browse Files...')) ?></span>
        <input class="fileupload" type="file" name="<?= $block->escapeHtmlAttr($block->getConfig()->getFileField()) ?>" data-url="<?= $block->escapeUrl($block->getConfig()->getUrl()) ?>" multiple>
    </span>
    <div class="clear"></div>
    <script type="text/x-magento-template" id="<?= $block->getHtmlId() ?>-template">
        <div id="<%- data.id %>" class="file-row">
            <span class="file-info"><%- data.name %> (<%- data.size %>)</span>
            <div class="progressbar-container">
                <div class="progressbar upload-progress" style="width: 0%;"></div>
            </div>
            <div class="clear"></div>
        </div>
    </script>
    <script>
        require([
            'jquery',
            'mage/template',
            'jquery/file-uploader',
            'domReady!',
            'mage/translate'
        ], function ($, mageTemplate) {
            $('#<?= $block->getHtmlId() ?> .fileupload').fileupload({
                dataType: 'json',
                formData: {
                    isAjax: 'true',
                    form_key: FORM_KEY
                },
                sequentialUploads: true,
                acceptFileTypes: /(\.|\/)(<?php echo implode($block->getAllowedExtensions());?>)$/i,
                maxFileSize: <?= $block->escapeJs($block->getFileSizeService()->getMaxFileSize()) ?>,
                add: function (e, data) {
                    var progressTmpl = mageTemplate('#<?= $block->getHtmlId() ?>-template'),
                        fileSize,
                        tmpl;

                    $.each(data.files, function (index, file) {
                        fileSize = typeof file.size == "undefined" ?
                            $.mage.__('We could not detect a size.') :
                            byteConvert(file.size);

                        data.fileId = Math.random().toString(36).substr(2, 9);

                        tmpl = progressTmpl({
                            data: {
                                name: file.name,
                                size: fileSize,
                                id: data.fileId
                            }
                        });

                        $(tmpl).data('image', data).appendTo('#<?= $block->getHtmlId() ?>');
                    });

                    $(this).fileupload('process', data).done(function () {
                        data.submit();
                    });
                },
                done: function (e, data) {
                    var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
                    var tempErrorMessage = document.createElement("div");
                    $(progressSelector).css('width', '100%');
                    $('[data-action="show-error"]').children(".message").remove();
                    if (data.result && !data.result.hasOwnProperty('errorcode')) {
                        $(progressSelector).removeClass('upload-progress').addClass('upload-success');
                    } else {
                        tempErrorMessage.className = "message message-warning warning";
                        tempErrorMessage.innerHTML = data.result.error;

                        $('[data-action="show-error"]').append(tempErrorMessage);
                        $(progressSelector).removeClass('upload-progress').addClass('upload-failure');
                    }
                },
                progress: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
                    $(progressSelector).css('width', progress + '%');
                },
                fail: function (e, data) {
                    var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
                    $(progressSelector).removeClass('upload-progress').addClass('upload-failure');
                }
            });

            $('#<?= $block->getHtmlId() ?> .fileupload').fileupload('option', {
                process: [{
                    action: 'load',
                    fileTypes: /^image\/(gif|jpeg|png)$/,
                    maxFileSize: <?= (int) $block->getFileSizeService()->getMaxFileSize() ?> * 10
            }, {
                action: 'resize',
                maxWidth: <?= (float) \Magento\Framework\File\Uploader::MAX_IMAGE_WIDTH ?> ,
                maxHeight: <?= (float) \Magento\Framework\File\Uploader::MAX_IMAGE_HEIGHT ?>
            }, {
                action: 'save'
            }]
        });
        });
    </script>
</div>
