import soap from "soap-as-promised";
import { getXml, parseResponse } from "./util";
import config from "./config";

const callGamma = async (methodSpecs, callParamsObject) => {
	try {
		const endpoint = config.endpoints[methodSpecs.endpoint];
		const client = await soap.createClient(endpoint);
		const callDetails = getXml(callParamsObject, methodSpecs);
		config.debug(`Using endpoint: ${endpoint}`);
		config.debug(callDetails);

		const rawResponse = await client.ReceiveData({ value: callDetails });
		config.debug(rawResponse.ReceiveDataResult);

		const response = parseResponse(rawResponse, methodSpecs);
		config.debug(JSON.stringify(response, null, 2));

		if (response.hasOwnProperty("Message")) throw new ReferenceError(response.Message);
		return response;
	} catch (error) {
		throw new Error(
			`The response from the Gamma server could not be parsed correctly. The error was "${JSON.stringify(
				error,
				null,
				2
			)}"`
		);
	}
};

export default callGamma;