import path from 'path';
import { writeFile } from 'fs/promises';
import { createReadStream } from 'fs';
import Minio from 'minio';
import { Readable } from 'stream';
const MINIO_ACCESS_KEY = 'tMhLrfog47lMm0HZ';
import { client } from '$lib/minio';
import { fail } from '@sveltejs/kit';

function isRequiredFieldValid(value) {
	if (value == null) return false;

	if (typeof value === 'string' || value instanceof String) return value.trim() !== '';

	return true;
}

/** @type {import('./$types').Actions} */
export const actions = {
	url: async ({ request }) => {
		const data = await request.formData();
		const vorgang = data.get('vorgang');
		const name = data.get('name');
		const type = data.get('type');
		const fileName = data.get('fileName');

		let objectName = `${vorgang}/${name}`;
		switch (type) {
			case 'image/png':
				if (!objectName.endsWith('.png')) objectName += '.png';
				break;
			case '':
				if (fileName.endsWith('.glb') && !objectName.endsWith('.glb')) objectName += '.glb';
		}

		const url = await client.presignedPutObject('tatort', objectName);

		return { url };
	},
	validate: async ({ request }) => {
		const requestData = await request.formData();
		const data = Object.fromEntries(requestData);
		const vorgang = data.vorgang;
		const name = data.name;
		let success = true;
		let err = {};

		if (isRequiredFieldValid(vorgang)) err.vorgang = null;
		else {
			err.vorgang = 'Das Feld Vorgang darf nicht leer bleiben.';
			success = false;
		}

		if (isRequiredFieldValid(name)) err.name = null;
		else {
			err.name = 'Das Feld Name darf nicht leer bleiben.';
			success = false;
		}

		if (success) return { success };

		return fail(400, err);
	},

	upload: async ({ request }) => {
		const requestData = await request.formData();
		const data = Object.fromEntries(requestData);
		const vorgang = data.vorgang;
		const name = data.name;
		console.log('I:', vorgang, name);

		const url = await client.presignedPutObject('tatort', `${vorgang}/${name}`, 60);

		console.log('O:', url);
		return { url };
	},
	upload3: async ({ request }) => {
		const requestData = await request.formData();
		const data = Object.fromEntries(requestData);
		const name = data.name;
		const stream = data.file.stream();
		console.log('Data:', stream);
		const metaData = { 'Content-Type': 'model-gtlf-binary', 'X-VorgangsNr': '4711' };
		const result = new Promise((resolve, reject) => {
			client.putObject('tatort', name, Readable.from(stream), metaData, function (err, etag) {
				if (err) return reject(err);
				resolve(etag);
			});
		});
		let etag = null;
		let error = null;
		try {
			etag = await result;
			console.log(etag);
		} catch (err) {
			error = err;
			console.log('Error:', err);
		}

		return { etag, error };
		//await writeFile(filePath, Buffer.from(await data.file.arrayBuffer()));
	}
};
