var $vars = {
    'selectThems': $("#selectThems"),
    'selectInterlocs': $("#selectInterlocs"),
    'thematiqueId': $("#app_bundle_depot_document_thematiqueId"),
    'interlocId': $("#app_bundle_depot_document_interlocId"),
    'themSpan': $(".themSpan"),
    'interSpan': $(".interSpan"),
    'extSpan': $(".extSpan"),
    'status': $("#js-status"),
    'submitFile': $("#submitFile"),
    'removeFile': $("#removeFile"),
    'uploadBar': $("#uploadBar"),
    'extensions': null
};

$("#js_depoDocStep").on("click", function () {

    $vars.themSpan.html($("#selectThems").find("option:selected").html());
    $vars.interSpan.html($("#selectInterlocs").find("option:selected").html());

    if ($("#selectThems").val() == "DPMO") {
        //TODO : REMPLACER URL PAR ROUTE DES DOSSIERS D'AIDES (LOT 5)
        window.location.replace(Routing.generate('homepage'));
    } else {
        $.getJSON(Routing.generate('thematique_extensions', {'code': $("#selectThems").find("option:selected").val(), 'siret': $("#selectInterlocs").find("option:selected").val()}), function (data) {
            if (data.length > 0) {
                $vars.extensions = data;
                $vars.extSpan.html(data.join());
            } else {
                $vars.extSpan.html('Toutes');
            }
        }).then(function () {
            sendEvent('#modal-multi-step-01', 2);
            // $vars.submitFile.hide(); ??
            $vars.uploadBar.css('width', '0%');
        });
    }
});

Dropzone.options.depoDropzone = {

    // Prevents Dropzone from uploading dropped files immediately
    autoProcessQueue: false,
    maxFiles: 1,
    createImageThumbnails: false,

    init: function () {
        var submitButton = document.querySelector("#submitFile"),
                removeButton = document.querySelector("#removeFile"),
                myDropzone = this; // closure

        submitButton.addEventListener("click", function () {
            myDropzone.processQueue(); // Tell Dropzone to process all queued files.
        });
        removeButton.addEventListener("click", function () {
            myDropzone.removeAllFiles();
        });

        this.on("addedfile", function (file) {
            // vérification de la présence d'un nom de fichier
            if (file.name = '') {
                swal({
                    title: "Attention !",
                    text: "Le nom du fichier doit être renseigné, veuillez le saisir.",
                    icon: "warning",
                    button: {
                        text: "OK",
                        className: "bg-orange hoverOpacity"
                    }
                })
            }
            ;
            if ($vars.extensions) {
                var ext = file.name.split('.');
                ext = ext[ext.length - 1];
                if (ext.length === 0) {
                    myDropzone.removeFile(file);
                    swal({
                        title: "Attention !",
                        text: "Votre fichier ne semble pas avoir d'extension, veuillez le vérifier.",
                        icon: "warning",
                        button: {
                            text: "OK",
                            className: "bg-orange hoverOpacity"
                        }
                    })
                } else if ($vars.extensions.indexOf(ext) === -1) {
                    myDropzone.removeFile(file);
                    swal({
                        title: "Attention !",
                        text: "Le fichier ne correspond pas aux extensions autorisées sur cette thématique.",
                        icon: "warning",
                        button: {
                            text: "OK",
                            className: "bg-orange hoverOpacity"
                        }
                    })
                }
            }

            if (file.size > (1024 * 1024 * 20)) // not more than 10mb
            {
                myDropzone.removeFile(file);
                swal({
                    title: "Attention !",
                    text: "Votre fichier excède 20mo !",
                    icon: "warning",
                    button: {
                        text: "OK",
                        className: "bg-orange hoverOpacity"
                    }
                })
            }

            $("#dz_img").hide();
            $vars.submitFile.show();
        });
        this.on("error", function (e, output) {
            let index = output.indexOf("Invalid JSON");
            if (index >= 0) {
                output = "Anomalie technique sur la fonction de dépôt ; veuillez ré-essayer ultérieurement";
            }
            swalError(myDropzone, output);
        });
        this.on("success", function (file, output) {
            $vars.uploadBar.css('width', '50%');
            $vars.uploadBar.css('width', '100%');
            var position = output.indexOf("CLOUD");

            if (position != -1) {
                swal({
                    title: "Attention!",
                    text: output,
                    type: "warning",
                    icon: "warning",
                }).then(function () {
                    var win = window.open(urlCloud, '_blank');
                    win.focus();
                    $(".modal").modal('hide');
                    sendEvent('#modal-multi-step-01', 1);
                    myDropzone.removeAllFiles();
                });
            } else {
                swal({
                    title: "Succès !",
                    text: output,
                    icon: "success",
                    button: {
                        text: "OK",
                        className: "bg-orange hoverOpacity"
                    }
                }).then(function () {
                    $(".modal").modal('hide');
                    sendEvent('#modal-multi-step-01', 1);
                    myDropzone.removeAllFiles();
                    window.location.replace(Routing.generate('homepage'))
                })
            }
        })
    }
};

function swalError(myDropzone, e) {
    swal({
        title: "Erreur !",
        text: e,
        icon: "error",
        button: {
            text: "OK",
            className: "bg-error-swal hoverOpacity"
        }
    }).then(function () {
        sendEvent('#modal-multi-step-01', 2);
        myDropzone.removeAllFiles();
    })
}