import * as XLSX from "xlsx";
//#region src/udp/fileImportMapping/fileUtils.js
const handleExcelFileUpload = (fileObject, fileProperties) => {
	return new Promise((resolve, reject) => {
		if (fileObject) {
			const reader = new FileReader();
			reader.onload = function(e) {
				const data = new Uint8Array(e.target.result);
				const workbook = XLSX.read(data, { type: "array" });
				const sheetName = workbook.SheetNames[fileProperties?.worksheetNumber?.value - 1];
				const worksheet = workbook.Sheets[sheetName];
				const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
				if (json.length > 1) {
					const headers = json[0];
					const firstDataLine = json[1];
					resolve({
						headers,
						sampleData: firstDataLine
					});
				} else reject("Could not get file headers");
			};
			reader.onerror = function() {
				reject("Error reading the file.");
			};
			reader.readAsArrayBuffer(fileObject);
		} else reject("No file provided");
	});
};
const handleTextFileUpload = (fileObject, fileProperties) => {
	return new Promise((resolve, reject) => {
		if (fileObject) {
			const chunkSize = 1024;
			let offset = 0;
			let accumulatedData = "";
			const reader = new FileReader();
			reader.onload = function(e) {
				accumulatedData += e.target.result;
				const lines = accumulatedData.split("\n");
				if (lines.length > 2) resolve({
					headers: lines[0].replace(/\r/g, "").split(fileProperties?.delimiter?.value),
					sampleData: lines[1].replace(/\r/g, "").split(fileProperties?.delimiter?.value)
				});
				else if (offset < fileObject.size) readNextChunk();
			};
			reader.onerror = function() {
				reject("Error reading the file.");
			};
			function readNextChunk() {
				const blob = fileObject.slice(offset, offset + chunkSize);
				reader.readAsText(blob);
				offset += chunkSize;
			}
			readNextChunk();
		} else reject("No file provided");
	});
};
const handleJsonFileUpload = (fileObject, fileProperties) => {
	return new Promise((resolve, reject) => {
		if (fileObject) {
			const reader = new FileReader();
			reader.onload = function(e) {
				try {
					const jsonData = JSON.parse(e.target.result);
					const dataAtPath = fileProperties?.jsonPath ? getValueByPath(jsonData, fileProperties?.jsonPath) : jsonData;
					if (Array.isArray(dataAtPath) && dataAtPath.length > 0) resolve({
						headers: Object.keys(dataAtPath[0]),
						sampleData: dataAtPath[0]
					});
					else reject("The JSON file does not contain an array or is empty.");
				} catch (err) {
					reject("Error parsing JSON file:", err);
				}
			};
			reader.onerror = function() {
				reject("Error reading the file.");
			};
			reader.readAsText(fileObject);
		} else reject("No file provided");
	});
};
const getValueByPath = (obj, path) => {
	return path.split(".").reduce((acc, key) => acc && acc[key], obj);
};
//#endregion
export { handleExcelFileUpload, handleJsonFileUpload, handleTextFileUpload };

//# sourceMappingURL=fileUtils.mjs.map