import { get } from "lodash";

/**
 * 必须是合法的标识符
 */
export const PLACEHOLDER_REGEXP = /\{\s*(['"a-zA-Z0-9_$.[\]]+)\s*\}/gm;

export function variableReplace(
  variables: Record<string, any>,
  local: Record<string, any>
) {
  Object.keys(variables).forEach((key) => {
    const value = variables[key];
    if (typeof value === "string") {
      const replaced = stringReplace(value, local);
      if (replaced !== value) {
        variables[key] = replaced;
      }
    }
  });

  return variables;
}

export function stringReplace(source: string, local: Record<string, any>) {
  // 快捷判断
  if (!source.includes("{")) {
    return source;
  }

  return source.replace(PLACEHOLDER_REGEXP, (m, p) => {
    return get(local, p);
  });
}
