const { createHash } = require('crypto');
const { seisjson, pdf } = require('../../lib/sse/present');
const { configuration } = require('../../lib/db');

function digestOf(content) {
	const hash = createHash('sha256');
	const data = (typeof content.data == "string" || Buffer.isBuffer(content.data))
		? content.data
		: JSON.stringify(content.data);
	hash.update(data);

	return {
		sha256: {hex: hash.digest('hex')}
	};
}

/**
 * Create the payloads to send to the ASAQC endpoint
 * for a queue item.
 *
 * At present this consists of two files, which must be
 * sent in two separate requests. One is the SeisJSON
 * file and the other is its PDF representation.
 *
 * In principle, other options are possible, such as
 * GeoJSON and CSV, and this could be made configurable.
 *
 * Likewise, it would be possible to upload P1 and P2 files,
 * etc.
 */
async function getPayloads(item) {

	const asaqcConfig = await configuration.get(item.payload.project, '/asaqc');
	const surveyName = await configuration.get(item.payload.project, 'id');

	const template = {
		type: "acqlinelog",
		imo: asaqcConfig.imo,
		mmsi: asaqcConfig.mmsi,
		surveyName: surveyName,
		surveyId: asaqcConfig.id
	};

	const seisjsonData  = await seisjson(item.payload);
	const pdfData = await pdf(item.payload, seisjsonData);

	return [
		{
			payload: {
				...template,
				fileName: seisjsonData.name,
				encodedData: Buffer.from(JSON.stringify(seisjsonData.data)).toString("base64")
			},
			digest: digestOf(seisjsonData)
		},
		{
			payload: {
				...template,
				fileName: pdfData.name,
				encodedData: pdfData.data.toString("base64")
			},
			digest: digestOf(pdfData)
		}
	]
}

module.exports = getPayloads;
