
/** Here write you dropzone config
 * start local config -->>
 * */
var localConfig = {
    /** soubory */
    files: {
        maxFiles: 20,
        acceptedFiles: "",
        complete: function (data) {
            if (data.xhr != null) {
                var response = $.parseJSON(data.xhr.response);

                if (data.status == 'success') {
                    var newElement = '<li class="dropzone__list__item" data-mime="pdf">'
                        + '<input type="hidden" name="' + getInputNameWithPrefix('files[' + response.id + '][file]', 'files') + '" value="' + response.id + '" />'
                        + '<input type="hidden" name="files[' + response.id + '][position]" value="" />'
//                                       +'<img src="' + fileContentURL + '?imgURL=' + response.fileURL + '" />''
                        + '<a href="">Současný soubor<br>' + response.fileName + '</a>'
                        + '<input class="dropzone__image__title"  type="text" value="" name="files[' + response.id + '][name]" placeholder="Název">'
                        + '<div class="dropzone__image__buttons"><button class="dropzone__image__button--close" type="button" onclick="getSpecificConfig(filesDropzone).removeRow(this.parentNode.parentNode);"></button></div>'
                        + '</li>';

                    $("#files-container").append(newElement);

                    // vymaz informace o nahravani
                    this.removeFile(data);
                    this.options.specificDefine.reindexFiles();

                }
            }
        },
        specificDefine: {
            reindexFiles: function () {
                $("#files-container li").each(function (index, element) {
                    var el = $(element);
                    var id = el.children("input:first-child").val();
                    el.children('[name="files[' + id + '][position]"]').val(index);
                })
            },
            removeRow: function (element) {
                element.parentNode.removeChild(element);
                this.reindexFiles();
            }
        }
    },

    images: {
        maxFiles: 30,
        acceptedFiles: "image/jpeg,image/png",
        complete: function (data) {
            if (data.xhr != null) {
                var response = $.parseJSON(data.xhr.response);

                if (data.status == 'success') {
                    var newElement = '<li class="dropzone__list__item">'
                        + '<input type="hidden" name="' + getInputNameWithPrefix('images[' + response.id + '][fileName]', 'images') + '" value="' + response.id + '" />'
                        + '<input type="hidden" name="' + getInputNameWithPrefix('images[' + response.id + '][position]', 'images') + '" value="" />'
                        + '<img src="' + this.options.specificDefine.fileContentURL + '?imgURL=' + response.fileURL + '" />'
                        + '<div class="dropzone__image__buttons">'
                        + '<button class="dropzone__image__button--close" type="button" onclick="getSpecificConfig(imagesDropzone).removeRow(this.parentNode.parentNode);"></button><br>'
                        + '<button class="dropzone__image__button--left" type="button" onclick="getSpecificConfig(imagesDropzone).turnDropzoneImageLeft(this.parentNode.parentNode);"></button>'
                        + '<button class="dropzone__image__button--right" type="button" onclick="getSpecificConfig(imagesDropzone).turnDropzoneImageRight(this.parentNode.parentNode);"></button>'
                        + '</div>'
                        + '<input type="hidden" name="images[' + response.id + '][turn]" value="0" />'
                        + '</li>';

                    $("#images-container").append(newElement);

                    // vymaz informace o nahravani
                    this.removeFile(data);

                    //reindexImages();
                }
            }
        },
        specificDefine: {
            reindexImages: function () {
                $("#images-container li").each(function (index, element) {
                    var el = $(element);
                    var id = el.children("input:first-child").val();
                    el.children('[name="images[' + id + '][position]"]').val(index);
                })
            },
            removeDropzoneRow: function (element) {
                element.parentNode.removeChild(element);
                this.reindexImages();
            },
            turnDropzoneImageRight: function (element) {
                var el = $(element);

                var rotation = el.data('rotation');
                if (!rotation) {
                    rotation = 0;
                }
                el.find('img').css('transform', 'rotate(' + (rotation + 90) + 'deg)');
                el.data('rotation', (rotation + 90));

                var id = el.children("input:first-child").val();
                var turn = el.children('[name="images[' + id + '][turn]"]').val();
                turn = parseInt(turn) - 90;
                el.children('[name="images[' + id + '][turn]"]').val(turn);
            },
            turnDropzoneImageLeft: function (element) {
                {
                    var el = $(element);

                    var rotation = el.data('rotation');
                    if (!rotation) {
                        rotation = 0;
                    }
                    el.find('img').css('transform', 'rotate(' + (rotation - 90) + 'deg)');
                    el.data('rotation', (rotation - 90));

                    var id = el.children("input:first-child").val();
                    var turn = el.children('[name="images[' + id + '][turn]"]').val();
                    turn = parseInt(turn) + 90;
                    el.children('[name="images[' + id + '][turn]"]').val(turn);
                }
            }

        }

    },

    /* jedna fotka*/
    oneImage: {
        maxFiles: 1,
        acceptedFiles: "image/jpeg,image/png",
        init: function () {
            var inputname = getInputNameWithPrefix('photoFileName', this);
            var imageURL = $("[name='" + inputname + "']").val();
            if (imageURL != '' && typeof (imageURL) !== 'undefined') {
                $(this.element).css("background-image", "url(" + imageURL + ")");
            }
        },
        complete: function (data) {
            if (data.xhr != null) {
                var response = $.parseJSON(data.xhr.response);
                if (data.status == 'success') {
                    var inputname = getInputNameWithPrefix('newPhotoFileName', this);
                    $("[name='" + inputname + "']").val(response.id);
                    $(this.element).css("background-image", "url(" + this.options.specificDefine.fileContentURL + '?imgURL=' + response.fileURL + ")");
                    $('.dz-preview').hide();
                    this.removeFile(data);
                }
            }
        },
        specificDefine: {
            turnDropzoneImageLeft: function (element) {
                var el = $(element); // wrapper
                var inputname = getInputNameWithPrefix('turn', this);
                console.log(inputname);
                var rotation = el.data('rotation');
                if (!rotation) {
                    rotation = 0;
                }
                el.find(this.selector).css('transform', 'rotate(' + (rotation - 90) + 'deg)');
                el.data('rotation', (rotation - 90));

                var turn = el.children('input[name="' + inputname + '"]').val();
                if (!turn)
                    turn = 0;
                turn = parseInt(turn) + 90;
                el.children('input[name="' + inputname + '"]').val(turn);
            },
            turnDropzoneImageRight: function (element) {
                var el = $(element); // wrapper
                var inputname = getInputNameWithPrefix('turn', this);

                var rotation = el.data('rotation');
                if (!rotation) {
                    rotation = 0;
                }
                el.find(this.selector).css('transform', 'rotate(' + (rotation + 90) + 'deg)');
                el.data('rotation', (rotation + 90));

                var turn = el.children('input[name="' + inputname + '"]').val();
                if (!turn)
                    turn = 0;
                turn = parseInt(turn) - 90;
                el.children('input[name="' + inputname + '"]').val(turn);
            },
            removeDropzoneImage: function (element) {

                var inputname1 = getInputNameWithPrefix('photoFileName', this);
                var inputname2 = getInputNameWithPrefix('newPhotoFileName', this);
                $('input[name="' + inputname1 + '"]').val('');
                $('input[name="' + inputname2 + '"]').val('');
                $(this.selector).css('background-image', 'none');
            }
        }
    },
    oneFile: {
        maxFiles: 1,
        acceptedFiles: "",
        init: function () {
            var inputname = getInputNameWithPrefix('newFileName', this);
            var fileName = $("[name='" + inputname + "']").val();
            if(fileName){
                setOneFileView($(this.element), fileName, 'pdf');
            }
        },
        sending: function () {
            this.options.specificDefine.nowUploading = true;
        },
        complete: function (data) {
            this.options.specificDefine.nowUploading = false;
            if (data.xhr != null) {
                var response = $.parseJSON(data.xhr.response);
                if (data.status == 'success') {
                    var inputname = getInputNameWithPrefix('newFileName', this);
                    $("[name='" + inputname + "']").val(response.id);
                    $('.dz-preview').hide();
                    this.removeFile(data);
                    setOneFileView($(this.element), response.fileName, response.dataType);
                }
            }
        },
        specificDefine: {
            nowUploading: false,
            removeDropzoneImage: function (element) {
                var inputname1 = getInputNameWithPrefix('fileName', this);
                var inputname2 = getInputNameWithPrefix('newFileName', this);
                $('input[name="' + inputname1 + '"]').val('');
                $('input[name="' + inputname2 + '"]').val('');
                unsetOneFileView($(element));
            }
        }
    },

    /* jedna fotka*/
    oneImageCustomFieldName: {
        maxFiles: 1,
        acceptedFiles: "image/jpeg,image/png",
        init: function () {
            var inputname = getInputNameWithPrefix(this.options.specificDefine.imageFileFieldName, this);
            var imageURL = $("[name='" + inputname + "']").val();
            if (imageURL != '' && typeof (imageURL) !== 'undefined') {
                $(this.element).css("background-image", "url(" + imageURL + ")");
            }
        },
        complete: function (data) {
            if (data.xhr != null) {
                var response = $.parseJSON(data.xhr.response);
                if (data.status == 'success') {
                    var inputname = getInputNameWithPrefix(this.options.specificDefine.newImageFileFieldName, this);
                    $("[name='" + inputname + "']").val(response.id);
                    $(this.element).css("background-image", "url(" + this.options.specificDefine.fileContentURL + '?imgURL=' + response.fileURL + ")");
                    $('.dz-preview').hide();
                    this.removeFile(data);
                }
            }
        },
        specificDefine: {
            turnDropzoneImageLeft: function (element) {
                var el = $(element); // wrapper
                var inputname = getInputNameWithPrefix('turn', this);

                var rotation = el.data('rotation');
                if (!rotation) {
                    rotation = 0;
                }
                el.find(this.selector).css('transform', 'rotate(' + (rotation - 90) + 'deg)');
                el.data('rotation', (rotation - 90));

                var turn = el.children('input[name="' + inputname + '"]').val();
                if (!turn)
                    turn = 0;
                turn = parseInt(turn) + 90;
                el.children('input[name="' + inputname + '"]').val(turn);
            },
            turnDropzoneImageRight: function (element) {
                var el = $(element); // wrapper
                var inputname = getInputNameWithPrefix('turn', this);

                var rotation = el.data('rotation');
                if (!rotation) {
                    rotation = 0;
                }
                el.find(this.selector).css('transform', 'rotate(' + (rotation + 90) + 'deg)');
                el.data('rotation', (rotation + 90));

                var turn = el.children('input[name="' + inputname + '"]').val();
                if (!turn)
                    turn = 0;
                turn = parseInt(turn) - 90;
                el.children('input[name="' + inputname + '"]').val(turn);
            },
            removeDropzoneImage: function (element) {

                var inputname1 = getInputNameWithPrefix('photoFileName', this);
                var inputname2 = getInputNameWithPrefix('newPhotoFileName', this);
                $('input[name="' + inputname1 + '"]').val('');
                $('input[name="' + inputname2 + '"]').val('');
                $(this.selector).css('background-image', 'none');
            }
        }
    },
    
    gallery: {
        maxFiles: 100,
        acceptedFiles: "image/jpeg,image/png",
        sending: function () {
            this.options.specificDefine.nowUploading = true;
        },
        complete: function (data) {
            this.options.specificDefine.nowUploading = false;
            if (data.xhr != null) {
                var response = data.xhr.response;
                if (data.status == 'success') {
                    
                    $("#images-container").append(response);

                    // vymaz informace o nahravani
                    this.removeFile(data);

                    reindexImages();
                }
            }
        },
        specificDefine: {
            nowUploading: false,
            reindexImages: function () {
                $("#images-container li").each(function (index, element) {
                    var el = $(element);
                    var id = el.children("input:first-child").val();
                    el.children('[name="images[' + id + '][position]"]').val(index);
                })
            },
            removeDropzoneRow: function (element) {
                element.parentNode.removeChild(element);
                reindexImages();
            },
            turnDropzoneImageRight: function (element) {
                var el = $(element);

                var rotation = el.data('rotation');
                if (!rotation) {
                    rotation = 0;
                }
                el.find('img').css('transform', 'rotate(' + (rotation + 90) + 'deg)');
                el.data('rotation', (rotation + 90));

                var id = el.children("input:first-child").val();
                var turn = el.children('[name="images[' + id + '][turn]"]').val();
                turn = parseInt(turn) - 90;
                el.children('[name="images[' + id + '][turn]"]').val(turn);
            },
            turnDropzoneImageLeft: function (element) {
                {
                    var el = $(element);

                    var rotation = el.data('rotation');
                    if (!rotation) {
                        rotation = 0;
                    }
                    el.find('img').css('transform', 'rotate(' + (rotation - 90) + 'deg)');
                    el.data('rotation', (rotation - 90));

                    var id = el.children("input:first-child").val();
                    var turn = el.children('[name="images[' + id + '][turn]"]').val();
                    turn = parseInt(turn) + 90;
                    el.children('[name="images[' + id + '][turn]"]').val(turn);
                }
            }

        }

    },
}

/* <--- end local config */



/* ------ functions and standart definitions of dropzone -------*/
/****************************************************************/
Dropzone.autoDiscover = false;
var objectConstructor = {}.constructor;

/*default config */
var defDropzoneConfig = {
    url: "",
    method: "post",
    paramName: "file", //define key in transfer array $_FILES
    addRemoveLinks: false,
    dictDefaultMessage: '',
    dictRemoveFile: "Odstranit fotku",
    dictCancelUpload: "Cancel Upload",
    dictCancelUploadConfirmation: "Do you want to cancel upload?",
    dictFallbackMessage: "Váš prohlížeč nepodporuje drag'n'drop nahrávání souborů.",
    dictFallbackText: "Prosím použijte formulář pro nahrávání souborů.",
    dictFileTooBig: "File is to big ({{filesize}}MB). Max.file size is: {{maxFilesize}}MB.",
    dictInvalidFileType: "Wrong file type",
    dictResponseError: "Server status: {{statusCode}}.",
    maxFilesize: ((typeof generalParams === 'undefined' 
                    || typeof generalParams.fileUploadMaxSize === 'undefined' 
                    || generalParams.fileUploadMaxSize === null) ? 2 : generalParams.fileUploadMaxSize), // MB
    maxFiles: 1,
    acceptedFiles: "",
    clickable: true,
    /**
     * dropzone.js dont use that
     * there define usable things - selectors, variable, constatnts
     */
    specificDefine: {
        contentURL: "", //define url to get file view (icon,picture)
        selector: "", //define selector of dropzone element
        formPrefix: ""     //if set name of formPrefix, there will by declared in json
    },

    init: function () {
    },
    sending: function (file, xhr, formData) {
    },
    error: function (data, errorMessage) {
        this.removeFile(data);
        alert(errorMessage);
    },
    complete: function (data) {
        // vymaz informace o nahravani
        this.removeFile(data);
    }
}

/**
 * Init, make dropzone on specific element
 * @param {type} selector - selector of dropzone element
 * @param {type} json - config json
 * @returns {Dropzone}
 */
function initDropzone(selector, json) {
    json.specificDefine.selector = selector;
    var dropzone = new Dropzone(selector, json);
    return dropzone;
}
/**
 * Get me local dropzone config by name
 * Vraci lokalni konfig dropzony dle jmena který je definovaný v localConfigu
 * @param {type} dropzoneType  - name of dropzone type
 * @returns {unresolved} json
 */
function getDropzoneConfig(dropzoneType) {
    var config = {};
//    if (typeof (localConfig) !== 'undefined' && typeof (localConfig[dropzoneType]) !== 'undefined') {
//        $.extend(config, defDropzoneConfig, localConfig[dropzoneType]);
//    } else {
//        config = defDropzoneConfig;
//    }
    if (typeof (localConfig) !== 'undefined' && typeof (localConfig[dropzoneType]) !== 'undefined') {
        config = $.extend(true, {}, config, defDropzoneConfig, localConfig[dropzoneType]);
    } else {
        config = $.extend(true, {}, config);
    }
    return config;
}

/**
 * Get specific define part of config by name
 * Vrat specific define cast konfigu, který je urceny svým názvem
 * @param {type} dropzoneType
 * @returns {config.specificDefine}
 */
function getSpecificConfig(dropzone) {
    var config = {};

    if (dropzone instanceof Dropzone) {
        return dropzone.options.specificDefine;
    } else {
        try {
            if (dropzone.constructor !== 'undefined' && dropzone.constructor === objectConstructor) {
                return dropzone;
            } else {
                return null;
            }
        } catch (err) {
            console.log(err);
            return null;
        }
    }

}

function getInputNameWithPrefix(inputName, dropzone) {
    var config = getSpecificConfig(dropzone);
    var name = inputName;
    try {
        var prefix = $.parseJSON(config.formPrefix);

        if (typeof (prefix) !== 'undefined' || prefix != "") {
            var inputName = "";

            if (prefix.length >= 1) {
                inputName += prefix[0];
            }
            for (var i = 1; i < prefix.length; i++) {
                inputName += '[' + prefix[i] + ']';
            }
            inputName += '[' + name + ']';
        }
    } catch (err) {
        console.log(err);
        return name;
    }
    return inputName;
}

/**
 * Set view of the box with file icon into Dropzone for One File
 * Nastaví náhled boxu s ikonou souboru do elemtnu Dropzony
 * @param {element} DOM element of the Dropzone
 * @param {fileName} name of the file
 * @param {mime} specific IZON identifier for mime-type
 */
function setOneFileView(element, fileName, mime) {
    str = '<div class="dropzone-one-file-preview" data-mime="' + mime + '"><span class="name">' + fileName + '</span></div>';
    $(element).append($(str));
}
/**
 * Unset view of the box with file icon from Dropzone for One File
 * Odstraní náhled boxu s ikonou souboru do elemtnu Dropzony
 * @param {element} DOM element of the Dropzone
 */
function unsetOneFileView(element) {
    console.log($(element));
    $(element).find('.dropzone-one-file-preview').remove();
}