/* $Header: svn://svn.omnis.net/branches/Studio10.1/Omnis_Master/CrossPlatform/jsworker/omnis_calls.js 22442 2019-03-23 14:39:44Z jgissing $ */
// Contains the interface that allows a method called via the Omnis JavaScript worker to send its response back to Omnis
// Copyright (C) OLS Holdings Ltd 2018

/*********************************** Changes History **********************************
Date			Edit				Bug					Description
23-Mar-19	jmg_unmarked						Updated sendResponse to base its response on the data that is passed in.
21-Nov-18	rmm_jsw									OW3 component - JavaScript Worker.
**************************************************************************************/

const omnis_calls = {

	/**
	 * Send any data as the response, attempting to automatically detect content type and convert data as necessary.
	 *
	 * @param data				The data to send back to Omnis.
	 * @param response		The 'response' object which was passed in to a module's 'call()' function.
	 */
	sendResponse: function(data, response) {
		response.statusCode = 200;
		if (data === null || typeof data === "undefined") { //  Send empty data for null/undefined
			response.setHeader("Content-Type", "text/plain;charset=utf-8");
			response.end("");
		}
		else if (data instanceof Buffer) { // Binary data
			response.setHeader("Content-Type", "application/octet-stream");
			response.end(data);
		}
		else if (data instanceof Object) { // Object or Array
			response.setHeader("Content-Type", "application/json;charset=utf-8");
			response.end(JSON.stringify(data));
		}
		else { // primitive type
			response.setHeader("Content-Type", "text/plain;charset=utf-8");
			response.end(data + ""); // Coerce into a string
		}
	},

	/**
	 * Send a buffer with any specified content type as the response.
	 * Use to explicitly specify the content type and data to send.
	 *
	 * @param data					The data to send.
	 * @param contentType		The MIME type of the data to send. E.g. "image/png"
	 * @param response			The 'response' object which was passed in to a module's 'call()' function.
	 */
	sendResponseBuffer: function(data, contentType, response) {
		response.statusCode = 200;
		response.setHeader("Content-Type", contentType);
		response.end(data);
	},

	/**
	 * Send an error status response.
	 *
	 * @param response		The 'response' object which was passed in to a module's 'call()' function.
	 * @param statusCode	An HTTP status code.
	 * @param errorText		A description of the error.
	 */
	sendError: function (response, statusCode, errorText) {
		response.statusCode = statusCode;
		response.setHeader("Content-Type", "text/plain;charset=utf-8");
		response.end(errorText);
	}
};

module.exports = omnis_calls;
