/**
 * Uploads
 * @see https://github.com/LPology/Simple-Ajax-Uploader
 */
IGDATAPOOLFE.plugins.add('upload', {
    form: null,
    initFields: function(form) {
	this.init(form);
    },
    init: function(form) {
	let $form = $(form);
	this.form = $form;
	$(document).on('click', 'a.delete-file', function(e) {
	    e.preventDefault();
	    var $this = $(this);

	    var $dpFileListItem = $this.closest('.dp-file-list-item');
	    var $dpFile = $dpFileListItem.closest('.dp-file');
	    var index = $dpFileListItem.data('index');
	    //console.log('delete=' + index +"=="+ $dpFileListItem.attr('data-index'));
	    var $dpFileHiddenField=$('.dp-file-hidden-field[data-index="' + index + '"]', $dpFile);
	    $dpFile.children('.dp-file-new').show();
	    $dpFileListItem.remove();
	    //$dpFile.children('.dp-file-list').html('');
	    $('select', $dpFileHiddenField).prop('selectedIndex', 0);
	    $('input.curFile', $dpFileHiddenField).val('');
	    $('input.newFile', $dpFileHiddenField).val('');
	    $('input.remove', $dpFileHiddenField).val('1');
	    $('input.origFilename', $dpFileHiddenField).val('');
	});
	$('.dp-file', $form).each(function() {
	    var $this = $(this);

	    var labels = $this.data('labels');
	    var phpOptions = $this.data('options');

	    var $button = $('.dp-file-newbutton', $this);
	    var $newDiv = $('.dp-file-new', $this);
	    var $dpFileHiddenFields = $('.dp-file-hidden-fields', $this);
	    var $mainInput = $('input.newFile', $this);
	    var $origFilenameInput = $('input.origFilename', $this);
	    var $fileList = $('div.dp-file-list', $this);
	    var $progressBar = $('div.dp-file-progress', $this);
	    var options = {
        hoverClass: 'ui-state-hover',
		button : $button,
		multiple : false,
		responseType : 'json',
		onExtError : function(filename, extension) {
		    $this.parent().siblings('.dp-errormsg').remove();
		    $('<div class="ig-inline dp-errormsg">' + labels.type_error + '</div>').insertAfter($this.parent());
		},
		onSizeError : function(filename, fileSize) {
		    $this.parent().siblings('.dp-errormsg').remove();
		    $('<div class="ig-inline dp-errormsg">' + labels.size_error + '</div>').insertAfter($this.parent());
		},
		onSubmit : function(filename, ext) {
            $form.find('[type="submit"]').attr('disabled', true);
            $form.find('[type="submit"]').prop('disabled', true);

		    $this.parent().siblings('.dp-errormsg').remove();
		    var $wrap = $('<div class="progressWrapper"></div>');
		    var $bar = $('<div class="dp-file-progressbar">&nbsp;</div>');
		    $wrap.append($bar);

		    $('.dp-file-progressBarWrapper', $progressBar).append($wrap);

		    this.setProgressBar($bar);
		    this.setProgressContainer($wrap);
		    $progressBar.show();
		},
		onProgress : function(pct) {
		    $('.dp-file-percentage', $progressBar).html(pct + '%');
		},
		onComplete : function(filename, response) {
            $form.find('[type="submit"]').attr('disabled', false);
            $form.find('[type="submit"]').prop('disabled', false);

		    if (!response) {
			$this.parent().siblings('.dp-errormsg').remove();
			$('<div class="ig-inline dp-errormsg">Fehler beim hochladen der Datei.</div>').insertAfter($this.parent());
			$progressBar.hide();
			$newDiv.show();
			return;
		    }

		    if (response.status == 'fail') {
			$this.parent().siblings('.dp-errormsg').remove();
			$('<div class="ig-inline dp-errormsg">Fehler beim hochladen der Datei.</div>').insertAfter($this.parent());
			$progressBar.hide();
			$newDiv.show();
			return;
		    }
		    //remove progress
		    $progressBar.hide();

		    //the value to pass to the propertymapper
		    var index='';
		    if( $dpFileHiddenFields.data('maxUploads')==1 ) {
			// only 1 File - no need to clone
			$newDiv.hide();
			$mainInput.val(response.value);
			$origFilenameInput.val(filename);
		    } else {
			var $current= $(".dp-file-hidden-field[data-empty=\"1\"]",$dpFileHiddenFields);
			var $clone=$current.clone();
			$clone.data('empty',0).attr('data-empty',0);
			$('input.newFile', $clone).val(response.value);
			$('input.origFilename', $clone).val(filename);
			$clone.insertBefore($current);
			name=$dpFileHiddenFields.data('name');
			index=$current.data('index');
			if(index === '') {
                            index = 0;
			} else {
                            index += 1;
			}
			$current.data('index', index).attr('data-index', index);
			$clone.data('index', index).attr('data-index',index);
			$('input', $clone).each(function( ) {$(this).attr('name',name + '[' + (index) + ']' + $(this).data('attribute'));});
			//console.log('clone['+name+'] index='+index +' to new.index='+(index+1));
		    }
		    var $msg=$(response.msg);
		    //console.log('change delete index=' + index);
		    $msg.data('index', index).attr('data-index',index);
		    //console.log($msg);
		    $fileList.append($msg);

		}
	    };

	    jQuery.extend(options, phpOptions);

	    var uploader = new ss.SimpleUpload(options);

	});
    }
});
