"use strict";

const React = require("react");
const classnames = require("classnames");
const defaultValue = require("default-value");

const extendClassnames = require("../extend-classnames");
const ThemeContext = require("./context");
const globalStyle = require("../../controls/glo-bal-style.css");

function mapThemeName(themeCSS, className, rulePrefix) {
	return themeCSS[`${rulePrefix}${className}`];
}

function mapDefaultName(defaultStyle, className) {
	return defaultStyle[className];
}

module.exports = function useTheme({ control, defaultStyle }) {
	let theme = React.useContext(ThemeContext);

	let rulePrefix = (control != null)
		? `${control}_`
		: "";

	function withTheme(classes) {
		if (arguments.length > 1) {
			console.warn(`WARNING: More than one argument specified to 'withTheme' call (second argument is ${JSON.stringify(arguments[1])})`);
		}

		let mappedClasses = extendClassnames(classes, (className) => {
			return [
				mapDefaultName(defaultValue(defaultStyle, {}), className),
				(theme != null)
					? mapThemeName(theme.css, className, rulePrefix)
					: null,
				mapDefaultName(globalStyle, "uilibComponent"),
				(theme != null)
					? mapThemeName(theme.css, "uilibComponent", "")
					: null,
			];
		});

		return classnames(... mappedClasses);
	}

	return { theme, withTheme };
};
