"use strict";

const Promise = require("bluebird");
const mmAxios = require("@modular-matrix/axios");
const getThumbnailURL = require("../get-thumbnail-url");
const withoutKeys = require("../without-keys");
const universalImageMetadata = require("../universal-image-metadata");
const defaultValue = require("default-value");

const { validateOptions } = require("@validatem/core");
const required = require("@validatem/required");
const requireEither = require("@validatem/require-either");
const isInteger = require("@validatem/is-integer");
const isBoolean = require("@validatem/is-boolean");
const defaultTo = require("@validatem/default-to");
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 getThumbnail(_options) {
	let options = validateOptions(arguments, [
		required,
		requireEither([ "session", "homeserver" ]),
		{
			session: [ isSession ],
			homeserver: [ isHomeserverURL ],
			url: [ required, isMXC ],
			method: [ required, oneOf([ "fit", "fill" ]) ],
			minimumWidth: [ required, isInteger ],
			minimumHeight: [ required, isInteger ],
			stream: [ isBoolean, defaultTo(false) ]
		}
	]);

	let axios = mmAxios({
		session: options.session,
		homeserver: options.homeserver
	});

	let thumbnailOptions = withoutKeys(options, [ "stream" ]);
	let url = getThumbnailURL(thumbnailOptions);

	return Promise.try(() => {
		return axios.get(url, {
			// TODO: Support "blob" in browsers?
			responseType: (options.stream === true) ? "stream" : "arraybuffer"
		});
	}).then((response) => {
		return Promise.try(() => {
			if (options.stream === false) {
				return universalImageMetadata(response.data);
			} else {
				return { width: undefined, height: undefined, mimetype: undefined };
			}
		}).then((metadata) => {
			return {
				buffer: (options.stream === false) ? response.data : undefined,
				stream: (options.stream === true) ? response.data : undefined,
				mimetype: defaultValue(metadata.mimetype, response.headers["content-type"]),
				width: metadata.width,
				height: metadata.height
			};
		});
	});
};
