"use strict";

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

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);

	console.log({ css: theme.css });

	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])})`);
		// }
		
		return syncpipe(classes, [
			(_) => _.filter((className) => className != null),
			(_) => extendClassnames(_, (className) => {
				return [
					mapDefaultName(defaultValue(defaultStyle, {}), className),
					(theme != null)
						? mapThemeName(theme.css, className, rulePrefix)
						: null,
					mapDefaultName(globalStyle, "uilibThemedElement"),
					(theme != null)
						? mapThemeName(theme.css, "uilibThemedElement", "")
						: null,
					// Special case: unprefixed control-independent class names -- FIXME: This check does not work for conditional class names!
					(className === "uilibComponent")
						? mapDefaultName(globalStyle, className)
						: null,
					(theme != null && className === "uilibComponent")
						? mapThemeName(theme.css, className, "")
						: null,
				];
			}),
			(_) => classnames(..._)
		]);
	}

	return { theme, withTheme };
};
