import fs from 'fs';
import path from 'path';
import { error } from "@sveltejs/kit";
import { getStreamInfo } from "$lib/database.js";
import { dev } from "$app/environment";
import { STREAM_JSON_LOCATION } from '$env/static/private';

let getOriginalJson, writeSideloadJson;
export let actions;

// utilities for manipulating original stream JSONs
if (dev) {
	const jsonFolder = path.resolve(STREAM_JSON_LOCATION);

	getOriginalJson = function (streamId) {
		const filePath = path.join(jsonFolder, streamId + ".sideload.json");
		if (fs.existsSync(filePath)) {
			const jsonString = fs.readFileSync(filePath, 'utf8');
			return jsonString;
		} else {
			return JSON.stringify({ 'title': '', 'description': '', 'tags': [] });
		}
	}

	writeSideloadJson = function (streamId, newJson) {
		const filePath = path.join(jsonFolder, streamId + ".sideload.json");
		fs.writeFileSync(filePath, JSON.stringify(newJson), 'utf8');
	}

	actions = {
		default: async ({ params, request }) => {
			const data = await request.formData();
			// let newJson = JSON.parse(getOriginalJson(params.stream_id));
			let newJson = {};
			newJson['title'] = data.get('title');
			newJson['description'] = data.get('description');
			newJson['tags'] = data.getAll('tags');
			writeSideloadJson(params.stream_id, newJson);
		}
	}
}

export function load({ params }) {
	const result = getStreamInfo(params.stream_id);
	if (result === null) {
		throw error(404);
	}

	if (dev) {
		// pass raw JSON for metadata editor
		let original = JSON.parse(getOriginalJson(params.stream_id));
		return {
			stream: result,
			original: original
		}
	} else {
		return {
			stream: result
		};
	}
}
