/***********
 This module is provided as an example of creating a Node PACKAGE, which could be published to NPM.

 Any modules within subfolders should be made into packages *create a package.json, e.g. by running 'npm init' in the directory).
 Otherwise NPM may clean up subfolders when running npm commands.
 **********/

const omnis_calls = await globalThis.loadModule("omnis_calls");
import fs from "node:fs/promises"


function sleep(ms) {
	return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * Implement all of your publicly accessible methods in methodMap.
 */
const methodMap = {

	progress: async function (param, response) {

		const { C1: iterationCount, C2: waitTime } = param;
		let iteration = 0;

		while (++iteration <= iterationCount) {
			omnis_calls.sendProgress({ iteration: iteration, totalIterations: iterationCount }, response);
			await sleep(waitTime);
		}

		return "All done";
	},

	test: function (param) {
		return {
			unicode: "Fingerspitzengef\xFChl is a German term.\nIt\u2019s pronounced as follows: [\u02C8f\u026A\u014B\u0250\u02CC\u0283p\u026Ats\u0259n\u0261\u0259\u02CCfy\u02D0l]"
		};
	},

	testParams: function (param, response) {
		const { program, version } = param;

		return omnis_calls.sendResponse(
			{ messageToShow: `You are running ${program} version ${version}` },
			response
		);
	},

	testError: function (param, response) {
		return omnis_calls.sendError(
			response,
			418,
			"an error occurred in our module's method!",
		);
	},

	testEvent: async function (param, response) {
		for (let i = 0; i < 100; i++) {
			await omnis_calls.sendEvent(
				{ loading_percent: i },
				response
			);

			await sleep(60);
		}
	},

	method: function (param, response) {
		omnis_calls.sendResponse(param, response); // Methods can (if they really need to) manually send a response, using the omnis_calls methods.
	},

	// Asynchronous methods should either be declared 'async' (in which case you can use 'await') 
	// or return a Promise, which you resolve.
	readpng: async function (param, response) {
		const data = await fs.readFile(param.path);
		return data;
	}
};

// omnis_calls.omnisModuleDefaultExport returns an object suitable for your default export.
// You must pass it your methodMap object.
export default omnis_calls.omnisModuleDefaultExport(methodMap);