"use strict";

const matchValue = require("match-value");

const addCommonFields = require("../event-add-common-fields");
const normalizeEncryptionAlgorithmName = require("../normalize-encryption-algorithm-name");
const mapMaybeRedacted = require("../map-maybe-redacted");

function mapFields(event) {
	let algorithm = normalizeEncryptionAlgorithmName(event.content.algorithm);

	return {
		// FIXME: decrypt method
		type: "encryptedMessage",
		algorithm: algorithm,
		senderKey: event.content.sender_key,
		... matchValue(algorithm, {
			"olm.curve25519.aes-cbc-256.sha-256": () => ({
				ciphertexts: Object.entries(event.content.ciphertext).map(([ deviceKey, payload ]) => {
					return {
						deviceKey: deviceKey,
						isPreKeyMessage: (payload.type === 0),
						ciphertext: payload.body
					};
				})
			}),
			"megolm.ed25519.aes-cbc-256.hmac-sha-256": {
				ciphertext: event.content.ciphertext,
				deviceID: event.content.device_id,
				sessionID: event.content.session_id
			}
		})
	};
}

module.exports = function mapEncryptedMessage(event, context) {
	if (context === "toDeviceEvent") {
		return mapFields(event);	
	} else {
		return addCommonFields(mapMaybeRedacted(event, () => {
			return mapFields(event);
		}));
	}
};
