/**********************
 * This file provides an example template as a possible way of implementing a simple Omnis JS Worker module.
 *
 * You just need to add functions to 'methodMap' for your methods.
 *********************/

const omnis_calls = require('omnis_calls');
const {errorCodes, newErrorWithCode} = require('./errors.js');
let autoSendResponse = true; // Set to false in methods which should not send a response to Omnis when they exit. (e.g. async methods)

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

	/************** EXAMPLE METHODS ***************/

	/**
	 * Example of a synchronous method.
	 * @param param		An object whose members match the column names of the Row parameter passed into $callmethod from Omnis.
	 * @return *			The data to return to Omnis.
	 */
	myMethod: function(param) {
		return { "result": 123 }; // Return value will automatically be sent to Omnis.
	},

	/**
	 * Example of a method which makes some asynchronous call, so cannot return its response data directly.
	 * @param param			An object whose members match the column names of the Row parameter passed into $callmethod from Omnis.
	 * @param response	The response object - must be passed to omnis_calls.sendResponse().
	 */
	myAsyncMethod: function(param, response) {
		autoSendResponse = false;
		// TODO: Manually call omnis_calls.sendResponse() or omnis_calls.sendError()
		// You MUST send the response, otherwise no further method calls will be processed.
	}

	/*************** TODO: Add methods here **************/

};


module.exports = {
	call: function (method, param, response) { // The only requirement of an Omnis module is that it implement this function.

		autoSendResponse = true;

		if (methodMap[method]) {
			const result = methodMap[method](param, response);
			if (autoSendResponse)
				omnis_calls.sendResponse(result, response);
			return true;
		}
		else {
			throw newErrorWithCode(errorCodes.METHOD_NOT_FOUND, "");
		}

	}
};