"use strict";

const url = require("url");

const makeURL = require("make-url");
const parseMXC = require("@modular-matrix/parse-mxc");

const { validateOptions } = require("@validatem/core");
const required = require("@validatem/required");
const requireEither = require("@validatem/require-either");
const isString = require("@validatem/is-string");
const isMXC = require("@modular-matrix/is-mxc-url");
const isSession = require("@modular-matrix/is-session");
const isHomeserverURL = require("@modular-matrix/is-homeserver-url");

module.exports = function getFileURL(_session, _options) {
	let options = validateOptions(arguments, [
		required,
		requireEither([ "session", "homeserver" ]),
		{
			session: [ isSession ],
			homeserver: [ isHomeserverURL ],
			url: [ required, isMXC ],
			filename: [ isString ]
		}
	]);

	let homeserverURL = (options.session != null)
		? options.session.homeserver
		: options.homeserver;

	let parsedMXC = parseMXC.parse(options.url);
	
	let urlTemplate = (options.filename != null)
		? "/_matrix/media/r0/download/:serverName/:mediaID/:filename"
		: "/_matrix/media/r0/download/:serverName/:mediaID";

	let path = makeURL(urlTemplate, {
		serverName: parsedMXC.homeserver,
		mediaID: parsedMXC.id,
		filename: options.filename
	});

	return url.resolve(homeserverURL, path);
};
