import { makeViewBoxSquare } from "../icon/square.js";
import { calculateSize } from "../svg/size.js";
import { iconToSVG } from "../svg/build.js";
import { svgToURL } from "../svg/url.js";
import { iconToHTML } from "../svg/html.js";

/**
* Generates common CSS rules for multiple icons, rendered as background/mask
*/
function getCommonCSSRules(options) {
	const result = {
		display: "inline-block",
		width: "1em",
		height: "1em"
	};
	const varName = options.varName;
	if (options.pseudoSelector) result["content"] = "''";
	switch (options.mode) {
		case "background":
			if (varName) result["background-image"] = "var(--" + varName + ")";
			result["background-repeat"] = "no-repeat";
			result["background-size"] = "100% 100%";
			break;
		case "mask":
			result["background-color"] = "currentColor";
			if (varName) result["mask-image"] = result["-webkit-mask-image"] = "var(--" + varName + ")";
			result["mask-repeat"] = result["-webkit-mask-repeat"] = "no-repeat";
			result["mask-size"] = result["-webkit-mask-size"] = "100% 100%";
			break;
	}
	return result;
}
/**
* Generate CSS rules for one icon, rendered as background/mask
*
* This function excludes common rules
*/
function generateItemCSSRules(icon, options) {
	const result = {};
	const varName = options.varName;
	const buildResult = iconToSVG(icon);
	let viewBox = buildResult.viewBox;
	if (viewBox[2] !== viewBox[3]) if (options.forceSquare) viewBox = makeViewBoxSquare(viewBox);
	else result["width"] = calculateSize("1em", viewBox[2] / viewBox[3]);
	const url = svgToURL(iconToHTML(buildResult.body.replace(/currentColor/g, options.color || "black"), {
		viewBox: `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}`,
		width: `${viewBox[2]}`,
		height: `${viewBox[3]}`
	}));
	if (varName) result["--" + varName] = url;
	else switch (options.mode) {
		case "background":
			result["background-image"] = url;
			break;
		case "mask":
			result["mask-image"] = result["-webkit-mask-image"] = url;
			break;
	}
	return result;
}
/**
* Generate content for one icon, rendered as content of pseudo-selector
*/
function generateItemContent(icon, options) {
	const buildResult = iconToSVG(icon);
	const viewBox = buildResult.viewBox;
	const height = options.height;
	const width = options.width ?? calculateSize(height, viewBox[2] / viewBox[3]);
	return svgToURL(iconToHTML(buildResult.body.replace(/currentColor/g, options.color || "black"), {
		viewBox: `${viewBox[0]} ${viewBox[1]} ${viewBox[2]} ${viewBox[3]}`,
		width: width.toString(),
		height: height.toString()
	}));
}

export { generateItemCSSRules, generateItemContent, getCommonCSSRules };