Dropzone.prototype.defaultOptions.dictDefaultMessage = "Drop files here to upload";
Dropzone.prototype.defaultOptions.dictFallbackMessage = "Your browser does not support drag'n'drop file uploads.";
Dropzone.prototype.defaultOptions.dictFallbackText = "Please use the fallback form below to upload your files like in the olden days.";
Dropzone.prototype.defaultOptions.dictFileTooBig = "Die maximale Dateigröße beträgt {{maxFilesize}}MB.";
Dropzone.prototype.defaultOptions.dictInvalidFileType = "You can't upload files of this type.";
Dropzone.prototype.defaultOptions.dictResponseError = "Server responded with {{statusCode}} code.";
Dropzone.prototype.defaultOptions.dictCancelUpload = "Cancel upload";
Dropzone.prototype.defaultOptions.dictCancelUploadConfirmation = "Are you sure you want to cancel this upload?";
Dropzone.prototype.defaultOptions.dictRemoveFile = "Remove file";
Dropzone.prototype.defaultOptions.dictMaxFilesExceeded = "You can not upload any more files.";
Dropzone.autoDiscover = false;

$(document).off('click touchstart', '[data-dz-delete]');
$(document).on('click touchstart', '[data-dz-delete]', function (e) {

    let file = $(this);

    console.log(e);
    // Prevent Click...
    e.preventDefault();

    // Confirmation
    let instance = limitlessNotification.set('Confirmation', 'Möchten Sie diese Datei wirklich löschen?', 'warning', true);

    // On confirm
    instance.get().on('pnotify.confirm', function() {

        // Get trigger for backend.
        $.get(file.attr('href'), function (data) {
            console.log("Data Loaded: " + data);
        });

        // Remove image
        file.parents('[dz-container]').hide();
    })

    // On cancel
    instance.get().on('pnotify.cancel', function() {

    });
})
$(document).on('click', '.DropzoneButton', function(e) {
    e.preventDefault();
})

function init() {

    let templateId = 'LimitlessDropzoneTemplate';

    setDropzoneButtons();
    setDropzone(templateId);
}

function initFiles(files, dropzoneId, templateId) {

    if(files.length == 0) return;

    files.forEach(function(file) {

        let templateObject = $('#' + templateId).clone();

        templateObject.show();
        templateObject.find('img').attr('src', file.thumbnailurl);
        templateObject.find('[data-dz-source]').attr('href', file.sourceurl);
        templateObject.find('[data-dz-delete]').attr('href', file.deleteurl);
        templateObject.find('[data-dz-name]').html(file.filename);
        templateObject.find('[data-dz-size]').html(file.filesize);
        templateObject.find('.align-items-start').css({'border':'1px dotted #888888'});

        $('#' + dropzoneId).append(templateObject.html());

    });

}

function setDropzoneButtons() {

    let counter = 0;

    $('.DropzoneButton').each(function() {
        counter++;
        let buttonElement = $(this);
        buttonElement.attr('id', 'DropzoneButton' + counter);
    });

}

function setDropzone(templateId) {

    let counter = 0;

    $('.LimitlessDropzone').each(function() {

        let element = $(this);
        let additionalConfig = element.attr('data-config') ? JSON.parse(element.attr('data-config')) : [];
        let files = element.attr('data-files') ? JSON.parse(element.attr('data-files')) : [];
        counter++;

        // adds auto generated id if element has no id
        if(!element.attr('id')) {
            let id = 'LimitlessDropzone' + counter;
            element.attr('id', id);
        }

        // Queueindicator
        let UIblocked = false;

        // Define and extend dropzone object.
        let DZ = $.extend({

                maxFilesize: 20,
                timeout: 90000,
                method: "post",
                thumbnailWidth: 120,
                thumbnailHeight: 100,
                acceptedFiles: "image/*,application/pdf",
                previewTemplate: document.getElementById(templateId).innerHTML,
                autoProcessQueue: true,
                clickable:'#DropzoneButton' + counter,
                success: function (file, response) {

                    // Saving successfull
                    let obj = $(file.previewTemplate);
                    obj.show();
                    obj.find('img').attr('src', response.thumbnailurl);
                    obj.find('[data-dz-source]').attr('href', response.sourceurl);
                    obj.find('[data-dz-name]').html(response.filename);
                    obj.find('[data-dz-size]').html(response.filesize);
                    obj.find('[data-dz-delete]').attr('href', response.deleteurl);

                    // Saving not successfull
                    if (response.sourceurl == undefined) {
                        obj.find('.list-icons').hide();

                        obj.find('.align-items-start').css({
                            'border': '1px solid #ff0000'
                        });

                        // Greyscale thumbnail on error.
                        obj.find('img').css({
                            '-webkit-filter': 'grayscale(100%)',
                            '-moz-filter': 'grayscale(100%)',
                            'filter': 'grayscale(100%)',
                            'opacity': '0.5'
                        });

                        limitlessNotification.set('', file.name + ": Der Uploadserver ist derzeit nicht verfügbar.", 'error');
                    }else{
                        limitlessNotification.set('', 'Die Datei wurde erfolgreich hochgeladen.', 'success');
                    }
                },
                processing: function () {

                    if(UIblocked == true)
                    {
                        return false;
                    }

                    UIblocked = true;

                    // Block UI while uploading...
                    $.blockUI({
                        message: '<i style="font-size: 5rem" class="icon-spinner6 spinner"></i>',
                        overlayCSS: {
                            backgroundColor: '#1b2024',
                            opacity: 0.8,
                            cursor: 'wait'
                        },
                        css: {
                            border: 0,
                            color: '#fff',
                            padding: 0,
                            backgroundColor: 'transparent'
                        }
                    });

                },
                queuecomplete: function () {

                    // Unblock UI when complete...
                    $.unblockUI();

                    UIblocked = false;

                },
                error: function (file, response) {

                    console.log(response);

                    if(response.message == '') response.message = '"dropconfig" URL nicht gefunden.';

                    // Error Message
                    limitlessNotification.set('', file.name + ": " + response.message, 'error');

                    // Greyscale thumbnail on error.
                    $(file.previewTemplate).find('img').css({
                        '-webkit-filter': 'grayscale(100%)',
                        '-moz-filter': 'grayscale(100%)',
                        'filter': 'grayscale(100%)',
                        'opacity': '0.5'
                    });

                    // Remove delete button on error.
                    $(file.previewTemplate).find('.list-icons').hide();

                    // Outline border in red on error.
                    $(file.previewTemplate).find('.align-items-start').css({
                        'border': '1px solid #ff0000'
                    });

                }
            },
            additionalConfig
        );

        // Start dropzone.
        element.dropzone(DZ);

        initFiles(files , element.attr('id'), templateId);
    });

}

$(document).ready(function() {
    init();
});

// $(document).ready(function()
// {
//
//     $('#<?php echo $array["id"]; ?>').find('button').click(function (e) {
//         e.preventDefault();
//     });
//
//
//     <?php foreach($array['files'] as $file){ ?>
//
//     var obj = $('#limitlessdropzonetemplate').clone();
//     obj.show();
//     obj.find('img').attr('src','<?php echo $file["thumbnailurl"]; ?>');
//     obj.find('[data-dz-source]').attr('href','<?php echo $file["sourceurl"]; ?>');
//     obj.find('[data-dz-delete]').attr('href','<?php echo $file["deleteurl"]; ?>');
//     obj.find('[data-dz-name]').html('<?php echo $file["filename"]; ?>');
//     obj.find('[data-dz-size]').html('<?php echo $file["filesize"]; ?>');
//     obj.find('.align-items-start').css({'border':'1px dotted #888888'});
//
//     $('#<?php echo $array["id"]; ?>').append(   obj.html()     );
//
//     <?php } ?>
//
// });