"use strict";

const React = require("react");
const asExpression = require("as-expression");

const useTheme = require("../../util/themeable");
const defaultStyle = require("./style.css");
const contexts = require("../../contexts");
const useGuaranteedMemo = require("../../util/use-guaranteed-memo");
const composeHandlers = require("../../util/compose-handlers");
const generateGridItemStyle = require("../../util/generate-grid-item-style");

module.exports = function ButtonSet({ x, y, horizontal, vertical, choice, onSelect, children }) {
	let { withTheme } = useTheme({ control: "buttonSet", defaultStyle });
	let [ selectedItem, setSelectedItem ] = React.useState();

	let handleOnClick = useGuaranteedMemo(() => {
		return composeHandlers([
			onSelect,
			setSelectedItem
		]);
	}, [ setSelectedItem ]);

	// FIXME: Validate horizontal, vertical - require one of
	// FIXME: Do below as post-processing in validation (like tags)
	let direction = (vertical === true)
		? "vertical"
		: "horizontal";

	let wrappedChildren = asExpression(() => {
		if (choice === true) {
			return (
				<contexts.button_onClick.Provider value={handleOnClick}>
					<contexts.button_selectedID.Provider value={selectedItem}>
						{children}
					</contexts.button_selectedID.Provider>
				</contexts.button_onClick.Provider>
			);
		} else {
			return children;
		}
	});

	return (
		<div className={withTheme("uilibComponent", "buttonSet", `direction-${direction}`)} style={generateGridItemStyle({ x, y })}>
			{wrappedChildren}
		</div>
	);
};
