"use strict";

const unreachable = require("@joepie91/unreachable");
const matchValue = require("match-value");
const defaultValue = require("default-value");

const normalizeEncryptionAlgorithmName = require("../normalize-encryption-algorithm-name");
const normalizePassphraseAlgorithmName = require("../normalize-passphrase-algorithm-name");

let keyIDRegex = /^m\.secret_storage\.key\.(.+)$/;

function getKeyID(type) {
	let match = keyIDRegex.exec(type);

	if (match != null) {
		return match[1];
	} else {
		unreachable("Event type did not match key ID regex");
	}
}

module.exports = function mapSecretStorageKeyEvent(event, _context) {
	let isDerived = (event.content.passphrase != null);
	let encryptionAlgorithm = normalizeEncryptionAlgorithmName(event.content.algorithm);

	let baseProperties = {
		type: "secretStorageKey",
		keyID: getKeyID(event.type),
		name: event.content.name,
		encryptionAlgorithm: encryptionAlgorithm,
		isDerivedFromPassphrase: isDerived
	};

	if (isDerived) {
		let passphraseData = event.content.passphrase;
		let passphraseAlgorithm = normalizePassphraseAlgorithmName(passphraseData.algorithm);
		
		let passphraseConfiguration = matchValue(passphraseAlgorithm, {
			"pbkdf2-sha512": {
				salt: passphraseData.salt,
				iterations: passphraseData.iterations,
				bitsToGenerate: defaultValue(passphraseData.bits, 256)
			}
		});

		return {
			... baseProperties,
			passphraseAlgorithm: passphraseData.algorithm,
			passphraseConfiguration: passphraseConfiguration,
			encryptionConfiguration: {}
		};
	} else {
		let encryptionConfiguration = matchValue(encryptionAlgorithm, {
			"aes-ctr-256.hmac-sha-256": {
				iv: event.content.iv,
				mac: event.content.mac
			}
		});

		return {
			... baseProperties,
			passphraseConfiguration: {},
			encryptionConfiguration: encryptionConfiguration
		};
	}
};
