/**
 * Uploads
 * @see https://github.com/LPology/Simple-Ajax-Uploader
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';
import VanillaUploader from '@dp/VanillaUploader';

const uploadPlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {
	document.addEventListener('click', function (e) {
	    let deleteButton = e.target;
	    while (deleteButton && !deleteButton.classList.contains('delete-file')) {
		deleteButton = deleteButton.parentElement;
	    }
	    if (deleteButton && deleteButton.classList.contains('delete-file')) {
		e.preventDefault();
		const dpFile = deleteButton.closest('.dp-file');
		let fileCount = parseInt(dpFile.getAttribute('data-file-count')) - 1;
		dpFile.setAttribute('data-file-count', fileCount);

		const dpFileListItem = deleteButton.closest('.dp-file-list-item');
		const index = dpFileListItem.getAttribute('data-index');

		// Remove the dp-file-list-item
		dpFileListItem.remove();
		const dpFileHiddenField = dpFile.querySelector('.dp-file-hidden-field[data-index="' + index + '"]');

		// Show the dp-file-new element
		const dpFileNewElement = dpFile.querySelector('.dp-file-new');
		dpFileNewElement.style.display = 'block';

		// Reset select element to the first option
		const selectElement = dpFileHiddenField.querySelector('select');
		if (selectElement) {
		    selectElement.selectedIndex = 0;
		}

		// Reset input elements
		const curFileInput = dpFileHiddenField.querySelector('input.curFile');
		const newFileInput = dpFileHiddenField.querySelector('input.newFile');
		const removeInput = dpFileHiddenField.querySelector('input.remove');
		const origFilenameInput = dpFileHiddenField.querySelector('input.origFilename');

		if (curFileInput) {
		    curFileInput.value = '';
		}
		newFileInput.value = '';
		if (removeInput) {
		    removeInput.value = '1';
		}
		origFilenameInput.value = '';
	    }
	});
	form.querySelectorAll('.dp-file').forEach((dpFile, i) => {
	    const labels = JSON.parse(dpFile.getAttribute('data-labels'));
	    const phpOptions = JSON.parse(dpFile.getAttribute('data-options'));
	    const button = dpFile.querySelector('.dp-file-newbutton');
	    const newDiv = dpFile.querySelector('.dp-file-new');
	    
	    const dpFileHiddenFieldsContainer = dpFile.querySelector('.dp-file-hidden-fields');
	    const mainInput = dpFile.querySelector('input.newFile');
	    const origFilenameInput = dpFile.querySelector('input.origFilename');
	    const fileList = dpFile.querySelector('div.dp-file-list');
	    const progressBar = dpFile.querySelector('div.dp-file-progress');

	    let options = {
		hoverClass: 'ui-state-hover',
		button : button,
		multiple : false,
		responseType : 'json',
		onExtError : function(filename, extension) {
		    dpFile.parentNode.querySelectorAll('.dp-errormsg').forEach(function (error) {
			error.remove();
		    });
		    const errorMsg = document.createElement('div');
		    errorMsg.className = 'ig-inline dp-errormsg';
		    errorMsg.textContent = labels.type_error;
		    dpFile.parentNode.insertBefore(errorMsg, dpFile.nextSibling);
		},
		onSizeError : function(filename, fileSize) {
		    dpFile.parentNode.querySelectorAll('.dp-errormsg').forEach(function (error) {
			error.remove();
		    });
		    const errorMsg = document.createElement('div');
		    errorMsg.className = 'ig-inline dp-errormsg';
		    errorMsg.textContent = labels.size_error;
		    dpFile.parentNode.insertBefore(errorMsg, dpFile.nextSibling);
		},
		onSubmit : function(filename, ext) {
		    let fileCount = parseInt(dpFile.getAttribute('data-file-count'));
		    let maxUploads = parseInt(dpFile.getAttribute('data-max-uploads'));
		    //console.log('onSubmit_ (fileCount: ' + fileCount + ', maxUploads=' + maxUploads + ')');
		    if (maxUploads > 0 && fileCount >= maxUploads) {
			return false;
		    }
		    fileCount++;
		    dpFile.setAttribute('data-file-count', fileCount);
		    form.querySelectorAll('[type="submit"]').forEach(function (submitButton) {
			submitButton.disabled = true;
		    });
		    dpFile.parentNode.querySelectorAll('.dp-errormsg').forEach(function (error) {
			error.remove();
		    });
		    // Create a new div element with the class "dp-file-progressbar"
		    const progressWrapper = document.createElement('div');
		    progressWrapper.className = 'progressWrapper';
		    const fileProgressBar = document.createElement('div');
		    fileProgressBar.className = 'dp-file-progressbar';
		    fileProgressBar.innerHTML = '&nbsp;'; // Add content if needed
		    
		    progressWrapper.appendChild(fileProgressBar);

		    const progressBarWrapper = dpFile.querySelector('.dp-file-progressBarWrapper');
		    progressBarWrapper.appendChild(progressWrapper);

		    this.setProgressBar(fileProgressBar);
		    this.setProgressContainer(progressWrapper);
		    progressBar.style.display = 'block';
			newDiv.style.display = 'none';
		},
		onProgress : function(pct) {
		    dpFile.querySelector('.dp-file-percentage').textContent = pct + '%';
		    //progressBar.querySelector('.dp-file-percentage').innerHTML = pct + '%';
		},
		onComplete : function(filename, response) {
		    form.querySelectorAll('[type="submit"]').forEach(function (submitButton) {
			submitButton.disabled = false;
		    });

		    dpFile.parentNode.querySelectorAll('.dp-errormsg').forEach(function (error) {
			error.remove();
		    });
		    if (!response || response.status === 'fail') {
			const errorMsg = document.createElement('div');
			errorMsg.className = 'ig-inline dp-errormsg';
			errorMsg.textContent = 'Fehler beim Hochladen der Datei.';
			dpFile.parentNode.insertBefore(errorMsg, dpFile.nextSibling);
			progressBar.style.display = 'none';
			newDiv.style.display = 'block';
			let fileCount = parseInt(dpFile.getAttribute('data-file-count')) - 1;
			dpFile.setAttribute('data-file-count', fileCount);
			return;
		    }
		    //remove progress
		    progressBar.style.display = 'none';
		    let maxUploads = parseInt(dpFile.getAttribute('data-max-uploads'));

		    //the value to pass to the propertymapper
		    let index = '';
		    if (maxUploads === 1) {
			newDiv.style.display = 'none';
			mainInput.value = response.value;
			origFilenameInput.value = filename;
		    } else {
			/*
			let current = null;
			for (var i = 0; i < dpFileHiddenFieldsContainer.length; i++) {
			    if (dpFileHiddenFieldsContainer[i].getAttribute('data-empty') === '1') {
				current = dpFileHiddenFieldsContainer[i];
				break; // Exit the loop once a matching element is found
			    }
			}
			*/
			let current = dpFileHiddenFieldsContainer.querySelector('.dp-file-hidden-field[data-empty="1"]');
			const clone = current.cloneNode(true);
			clone.setAttribute('data-empty', '0');
			clone.querySelector('input.newFile').value = response.value;
			clone.querySelector('input.origFilename').value = filename;

			const name =  dpFileHiddenFieldsContainer.dataset.name;
			index = current.getAttribute('data-index');
			if (index === null || index === '') {
			    index = 0;
			} else {
			    // Convert the 'data-index' attribute value to a number and increment it
			    index = parseInt(index, 10) + 1;
			}
			current.setAttribute('data-index', index);
			clone.setAttribute('data-index', index);
			clone.querySelectorAll('input').forEach(function(input) {
			    input.name = name + '[' + index + ']' + (input.dataset.attribute === undefined ? '' : input.dataset.attribute);
			});
			current.parentNode.insertBefore(clone, current);
		    }

		    const msg = document.createElement('div');
		    msg.innerHTML = response.msg;
		    const fileListItem = msg.firstElementChild;
		    fileListItem.setAttribute('data-index', index);
		    fileList.appendChild(fileListItem);
		}
	    };
	    Object.assign(options, phpOptions);
	    var uploader = new VanillaUploader(options);
	});
    }
};

IGDATAPOOLFE.addPlugin('upload', uploadPlugin);
export default uploadPlugin;

