"use strict";

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

let standardRegex = /^m\.([\s\S]+)$/u;
let userRegex =  /^u\.([\s\S]+)$/u;
let clientRegex = /^((?:[^.]+\.){2,})([\s\S]+)$/u;

function parseTag(tag) {
	let match;
	
	if (match = standardRegex.exec(tag)) {
		return {
			type: "standard",
			name: matchValue(match[1], {
				lowpriority: "isLowPriority",
				favourite: "isFavourite",
				server_notice: "isServerNoticeRoom"
			})
		};
	} else if (match = userRegex.exec(tag)) {
		return {
			type: "user",
			name: match[1]
		};
	} else if (match = clientRegex.exec(tag)) {
		return {
			type: "client",
			namespace: match[1],
			name: match[2]
		};
	} else {
		// Legacy, un-namespaced format
		return {
			type: "user",
			name: tag
		};
	}
}

module.exports = function mapTagEvent(event, _context) {
	return {
		type: "tagsChanged",
		tags: Object.entries(event.content.tags).map(([ tagString, options ]) => {
			return {
				... parseTag(tagString),
				tagString: tagString,
				// TODO: Explicitly parse options?
				options: options
			};
		})
	};
};
