import { Uppy, Dashboard, XHRUpload } from "https://releases.transloadit.com/uppy/v3.15.0/uppy.min.mjs";

// var uppy = new Uppy({
// onBeforeFileAdded: (currentFile, files) => {
	
// 	//const name = Date.now() + '_' + currentFile.name
// 	const month = (new Date().getMonth() + 1).toString().padStart(2, '0');
// 	const day = (new Date().getDate()).toString().padStart(2, '0');
// 	const name = `${new Date().getFullYear()}_${month}_${day}_${currentFile.name}`;
// 	console.log(name);
// 	const modifiedFile = {
// 		...currentFile,
// 		meta: {
// 			...currentFile.meta,
// 			name
// 		},
// 		name
// 	};
// 	return modifiedFile
// }})

var uppy = new Uppy({
onBeforeFileAdded: (currentFile, files) => {

	const month = (new Date().getMonth() + 1).toString().padStart(2, '0');
	const day = (new Date().getDate()).toString().padStart(2, '0');

	// Menghilangkan koma (,) dalam nama file
	const sanitizedFileName = currentFile.name.replace(/,/g, '');

	// 				TAHUN-BULAN-HARI_TIMESTAMP - NAMA_FILE
	const name = `${new Date().getFullYear()}-${month}-${day}_${Date.now()} - ${sanitizedFileName}`;

	// Membuat objek file yang dimodifikasi
	const modifiedFile = {
	...currentFile,
	meta: {
		...currentFile.meta,
		name
	},
	name
	};

	return modifiedFile;
}
})

.use(Dashboard, {
	inline: true,
	target: "#drag-drop-area",
	width: '100%',
	height: 300,
})

.use(XHRUpload, { endpoint: "/activities/upload", method: 'post' });

uppy.on("complete", (result) => {
	let array = result.successful;
	let arrtext = [];

	for (let i = 0; i < array.length; i++) {
		let text = result.successful[i].name;
		arrtext.push(text);
	}

	let text = arrtext.join();

	$('#attachment').val(function(){
		if (this.value == '') {
			return this.value + text;
		} else if (this.value != ''){
			return this.value + ',' + text;
		}
	});

	console.log( "Upload complete! We’ve uploaded these files:", result.successful);
});

/*
const attachmentList = document.querySelector('#attachment').value;
const arrayx = attachmentList ? attachmentList.split(',') : [];
arrayx.forEach((fileName) => {
	fetch(`<?=base_url();?>/upload/${fileName}`)
	.then((response) => response.blob())
	.then((blob) => {
	uppy.addFile({
		name: fileName.substring(11),
			type: blob.type,
			data: blob,
		});

		if (fileName === arrayx[arrayx.length - 1]) {
			uppy.getFiles().forEach((file) => {
				uppy.setFileState(file.id, {
				progress: { uploadComplete: true, uploadStarted: true },
				});
			});
		}
	});
});
*/
