import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useVariables from "../hooks/useVariables.js";
import { getVariableKey } from "../provider/variables/utils.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { isArr, isString } from "@pisell/utils";
import { useMemoizedFn } from "ahooks";
//#region src/components/dataSourceComponents/dataSourceShow/utils.tsx
const parseValueToVariableKey = (value) => {
	if (isArr(value) && value.length === 1 && isString(value[0])) {
		const key = getVariableKey(value[0]);
		return key ? key.split(".")[0] : null;
	}
	if (isString(value)) {
		const key = getVariableKey(value);
		return key ? key.split(".")[0] : null;
	}
	return null;
};
const withParseVariables = (Component, keys) => {
	return (props) => {
		const [variables, setVariables] = useState({});
		const { parseVariable, subscribeVariables } = useVariables();
		const valuesRef = useRef(/* @__PURE__ */ new Set());
		const handleVariableChange = useMemoizedFn((allVariables, updateVariables) => {
			const changedKey = Object.keys(updateVariables)[0];
			if (valuesRef.current.has(changedKey)) setVariables((prev) => _objectSpread2(_objectSpread2({}, prev), allVariables));
		});
		useEffect(() => {
			const values = /* @__PURE__ */ new Set();
			keys.forEach((key) => {
				const variableKey = parseValueToVariableKey(props[key]);
				if (variableKey) values.add(variableKey);
			});
			valuesRef.current = values;
		}, [props, keys]);
		useEffect(() => {
			const unsubscribe = subscribeVariables === null || subscribeVariables === void 0 ? void 0 : subscribeVariables(handleVariableChange);
			return () => {
				unsubscribe === null || unsubscribe === void 0 || unsubscribe();
			};
		}, []);
		const parsedProps = useMemo(() => {
			const result = _objectSpread2({}, props);
			keys.forEach((key) => {
				const value = props[key];
				if (isArr(value) && value.length === 1 && isString(value[0])) result[key] = parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(value[0], variables);
				else if (isString(value)) result[key] = parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(value, variables);
			});
			return result;
		}, [
			props,
			variables,
			keys
		]);
		return /* @__PURE__ */ React.createElement(Component, parsedProps);
	};
};
//#endregion
export { withParseVariables as default };
