"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("../require-either");
const isInteger = require("@validatem/is-integer");
const oneOf = require("@validatem/one-of");
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 getThumbnailURL(_session, _options) {
	let options = validateOptions(arguments, [
		required,
		requireEither([ "session", "homeserver" ]),
		{
			session: [ isSession ],
			homeserver: [ isHomeserverURL ],
			url: [ required, isMXC ],
			method: [ required, oneOf([ "crop", "scale" ]) ],
			minimumWidth: [ required, isInteger ],
			minimumHeight: [ required, isInteger ]
		}
	]);

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

	let parsedMXC = parseMXC.parse(options.url);
	
	let path = makeURL("/_matrix/media/r0/thumbnail/:serverName/:mediaID", {
		serverName: parsedMXC.homeserver,
		mediaID: parsedMXC.id
	});

	return url.resolve(homeserverURL, url.format({
		pathname: path,
		query: {
			method: options.method,
			width: options.minimumWidth,
			height: options.minimumHeight
		}
	}));
};
