"use strict";

const Promise = require("bluebird");

const mmAxios = require("@modular-matrix/axios");
const generateTransactionID = require("../generate-transaction-id");
const makeURL = require("make-url");

const { validateArguments } = require("@validatem/core");
const required = require("@validatem/required");
const isPlainObject = require("@validatem/is-plain-object");
const isString = require("@validatem/is-string");
const isRoomID = require("../is-room-id");
const isSession = require("@modular-matrix/is-session");

/* TODO:
- Retries
- Send queue
*/

module.exports = function sendMessageEvent(_session, _options) {
	let [ session, options ] = validateArguments(arguments, {
		session: [ required, isSession ],
		options: [ required, {
			roomID: [ required, isRoomID ],
			type: [ required, isString ],
			content: [ required, isPlainObject ]
		}]
	});

	let axios = mmAxios({ session: session });
	let transactionID = generateTransactionID();

	return Promise.try(() => {
		let url = makeURL("/client/r0/rooms/:roomID/send/:type/:transactionID", {
			roomID: options.roomID,
			type: options.type,
			transactionID: transactionID
		});

		return axios.put(url, options.content, {
			sendQueueKey: options.roomID
		});
	}).then((response) => {
		return {
			eventID: response.data.event_id
		};
	});
};
