Dropzone.autoDiscover = false;

var FormDropzone = function () {
    return {
        //main function to initiate the module
        init: function (parent) {


            window.DropzoneDefaults = {
                dictDefaultMessage: Translator.trans('cs_core.assets.widget.dictDefaultMessage'),
                dictFallbackMessage: Translator.trans('cs_core.assets.widget.dictFallbackMessage'),
                dictFallbackText: Translator.trans('cs_core.assets.widget.dictFallbackText'),
                dictFileTooBig: Translator.trans('cs_core.assets.widget.dictFileTooBig'),
                dictInvalidFileType: Translator.trans('cs_core.assets.widget.dictInvalidFileType'),
                dictResponseError: Translator.trans('cs_core.assets.widget.dictResponseError'),
                dictCancelUpload: Translator.trans('cs_core.assets.widget.dictCancelUpload'),
                dictCancelUploadConfirmation: Translator.trans('cs_core.assets.widget.dictCancelUploadConfirmation'),
                dictRemoveFile: Translator.trans('cs_core.assets.widget.dictRemoveFile'),
                dictRemoveFileConfirmation: Translator.trans('cs_core.assets.widget.dictRemoveFileConfirmation'),
                dictMaxFilesExceeded: Translator.trans('cs_core.assets.widget.dictMaxFilesExceeded'),
                init: function() {
                    var _dropzone = this;
                    var $element = $(this.element);

                    this.type = $element.data('dropzone-type');
                    this.contentType = $element.data('content-type');
                    this.multiple = $element.data('multiple');
                    this.widgetContainer = $element.parents('.assets-widget:first');
                    this.libraryContainer = this.widgetContainer.find('.widget-asset-library');
                    this.elementContainer = this.widgetContainer.find('.cs-selected-assets');
                    this.inputContainer = $element;
                    this.inputName = $element.data('name');
                    this.checkContainer = (function() {

                        var inputs = this.inputContainer.find('input[data-asset]');

                        if(!this.multiple) {
                            if(inputs.length) {
                                $(this.widgetContainer).children().not(this.elementContainer).slideUp();
                            } else {
                                $(this.widgetContainer).children().not(this.elementContainer).slideDown();
                            }

                        }
                    }).bind(this);

                    this.on('sending', function(file, xhr, formData) {
                        formData.append('type', _dropzone.type);
                        formData.append('contentType', _dropzone.contentType);
                    });

                    this.on('success', function (file, response) {

                        var element = $(file.previewElement);
                        element = FormDropzone.buildTemplate(element, this.multiple, false, this.widgetContainer);

                        if($.isPlainObject(response) && response.status != 200) {
                            AssetsHelper.removeSelected(_dropzone.element, element.data('id-content'));
                            _dropzone.checkContainer();
                            element.remove();
                            showToastrNotification('error', DropzoneDefaults.dictFallbackText);
                            return;
                        }

                        element.attr('id', 'library-asset-' + response.metadata.id + '_selected');

                        //Add editable link
                        // var editUrl = Routing.generate('admin_assets_edit', {id: response.metadata.id });
                        var editUrl = "domain.com";
                        element.find('[data-type="edit-link"]').attr('href', editUrl).fadeIn('slow');
                        element.find('.btn-remove').fadeIn('slow');

                        var _this = this;

                        ErrorHandler.handle(response.status);

                        var titleInput = element.find('input[data-entity="title"]');
                        element.data('id-content', response.metadata.id);
                        element.attr('data-id-content', response.metadata.id);

                        var title = '';

                        if(response.metadata.hasOwnProperty('title')) {
                            title = response.metadata.title;
                        }

                        if (this.widgetContainer.find('[data-upload-locale]').length > 1) {
                            $.each(this.widgetContainer.find('[data-upload-locale]'), function () {
                                var option = AssetsHelper.createOptionFromDiv($(this), title);
                                AssetsHelper.afterUploadLocaleCreation(title, $(this).attr("data-lang-code"), response.metadata.id);

                                if ($(this).attr("data-lang-code") === $(this).attr("data-default")) {
                                    AssetsHelper.selectDefaultOptionAndSetTitle(option, titleInput);
                                }

                                element.find('select[data-lang-field-selector]').append(option);

                                AssetsHelper.langChangeEvent(element);
                            });
                        } else {
                            var localeCode = this.widgetContainer.find('[data-lang-name]').attr("data-lang-code");
                            AssetsHelper.afterUploadLocaleCreation(title, localeCode, response.metadata.id);
                            titleInput.val(title);
                            titleInput.attr("data-title-locale", localeCode);
                            element.find('[data-lang-field-delete]').remove();
                        }

                        AssetsHelper.setLangBeforeChange(element);
                        AssetsHelper.bindTitleInput(element, title);
                        AssetsHelper.addSelected(_dropzone.element, response.metadata.id);
                        AssetsHelper.signals.onNewAdd.dispatch(this.widgetContainer, $(file.previewElement));
                        AssetsHelper.signals.onNewCreate.dispatch(response, this.widgetContainer);

                    });

                    this.on("error", function(file, message) {
                        var _this = this;
                        _this.removeFile(file);
                        showToastrNotification('error', message);
                    });

                    this.on("processing", function(file) {
                        return false;
                    });

                    this.on("addedfile", function(file) {
                        // Capture the Dropzone instance as closure.
                        var _this = this;

                        // Add the button to the file preview element.
                        var element = $(file.previewElement);
                        element = FormDropzone.buildTemplate(element, this.multiple,true, this.widgetContainer);


                        if('image' != _dropzone.type) {
                            element.find('[data-dz-thumbnail]').attr('src', '/bundles/comitium5designer/layout/img/asset-' + _dropzone.type + '.gif');
                        }

                        if (!_dropzone.widgetContainer.data('insert') || _dropzone.widgetContainer.data('insert') == 'append') {
                            element.appendTo(_dropzone.elementContainer);
                        } else {
                            element.prependTo(_dropzone.elementContainer);
                        }


                        // Listen to the click event
                        element.find('.btn-remove').on("click", function(e) {
                          // Make sure the button click doesn't submit the form:
                          e.preventDefault();
                          e.stopPropagation();

                            AssetsHelper.signals.onNewRemove.dispatch(_dropzone.widgetContainer, $(file.previewElement));

                            $.ajax({
                                url: Routing.generate('designer_assets_delete', { type: _dropzone.type }),
                                method: 'POST',
                                data: {
                                    'type': _dropzone.type,
                                    'ids': element.data('id-content'),
                                    'toast': 0
                                },
                                success: function(data) {
                                    if(data.status != 200) {
                                        return;
                                    }
                                    _this.removeFile(file);
                                    AssetsHelper.removeSelected(_dropzone.element, element.data('id-content'));
                                    _this.checkContainer();
                                    AssetsHelper.signals.onNewAfterRemove.dispatch(_dropzone.widgetContainer, $(file.previewElement));
                                }
                            });


                        });

                    });
                },
                previewTemplate:
                "<div class=\"row asset-wrapper cs-selectable\">" +
                    "<div class=\"image-inner\">" +
                        "<div class=\"col-md-3 col-xs-4 image\">" +
                            "<img data-dz-thumbnail=\"\" />" +
                            "<span class=\"opts\">" +
                                "<a href=\"#\" class=\"btn btn-icon-only btn-circle default btn-edit blue\" data-type=\"edit-link\" target=\"_blank\" style=\"display: none\">" +
                                "<i class=\"fa fa-pencil\"></i>" +
                                "</a>" +
                                "<a href=\"#\" class=\"btn btn-icon-only btn-circle red btn-remove\" style=\"display: none\"> " +
                                "<i class=\"fa fa-times\"></i>" +
                                "</a>" +
                            "</span>" +
                            "<div class=\"dz-progress\">" +
                                "<span class=\"dz-upload\" data-dz-uploadprogress></span>" +
                            "</div>" +
                        "</div>" +
                        "<div class=\"col-md-9 col-xs-8 image-info input-group portlet-sortable-empty\" data-lang-field-container>" +
                            '<div class="input-group-btn" data-lang-field-delete>' +
                                '<select id="search-order" class="bs-select form-control no-select2" data-style="clean" data-lang-field-selector>' +
                                '</select>' +
                            '</div>' +
                            "<div class=\"input-icon\">" +
                                "<i class=\"fa fa-pencil\"></i>" +
                                "<input type=\"text\" class=\"form-control\" data-entity=\"title\" placeholder=\"Untitled\" />" +
                            "</div>" +
                            "<!-- <div class=\"link\"> <i class=\"fa fa-link\"></i> <a href=\"http://192.168.1.42/metronic/theme/templates/admin/form_editable.html\" id=\"link\" data-type=\"text\" data-pk=\"1\" data-original-title=\"Set link\">Set link</a> </div> --> " +
                            "<div class=\"dz-error-message\">" +
                                "<span data-dz-errormessage></span>" +
                            "</div>" +
                        "</div>" +
                    "</div>" +
                "</div>",
            };

            if(!parent) {
                parent = $('body');
            }

            // @TODO (Allow multiple and parallel upload11)
            $('.assets-dropzone', parent).each(function() {

                $this = $(this);

                var overrideOptions = {
                    url: $this.data('url'),
                    acceptedFiles: $this.data('mime-types') ? $this.data('mime-types') : AssetsHelper.acceptedMimeTypes[$this.data('dropzone-type')],
                    uploadMultiple: false,
                    parallelUploads: 1,
                    maxFiles: ($this.data('multiple') ? null : 1)
                };


                var options = $.extend(DropzoneDefaults, overrideOptions);

                $(this).dropzone(options);
            });
        },
        buildTemplate: function(template,multiple,generate, widget) {

            if (!generate) {
                return template;
            }

            if (!multiple || multiple === 'false' || !widget.data('is_advanced')) {
                return template;
            }

            var addon = '<div class="checkbox-list">\
                <div class="checker"><span class=""><input type="checkbox" data-action="select"></span></div></div>\
                <div class="clearfix"></div>\
                    <div class="input-group margin-top-10 portlet-sortable-empty gf-spinner">\
                        <input aria-required="true" class="form-control spinner-input input-small" type="text" data-action="position">\
                        <button type="button" class="btn spinner-up default">\
                            <i class="fa fa-angle-down"></i>\
                        </button><button type="button" class="btn spinner-down default">\
                        <i class="fa fa-angle-up"></i>\
                    </button>\
                </div>';

            template.find('.image-info').append(addon);

            return template;
        }
    };
}();
