import { ObjectValue, Step } from "../shared";
import Node from "./Node";

export default function getNodePath(
  parent: Node | null,
  step: Step | null
): string {
  return `${
    parent ? `${getNodePath(parent.props.parent, parent.props.step)} > ` : ""
  }${
    !step
      ? "{}"
      : step.type === "GetFieldStep"
        ? `${step.fieldName}(${JSON.stringify(step.fieldArguments)})`
        : `[${step.index}]`
  }`;
}

export function getJsonNodePathAndArgs(
  parent: Node | null,
  step: Step | null
): { path: string; args: { [path: string]: ObjectValue } } {
  const { path: basePath, args } = parent
    ? getJsonNodePathAndArgs(parent.props.parent, parent.props.step)
    : { path: "", args: {} };

  const path = `${basePath}${
    !step
      ? ""
      : step.type === "GetFieldStep"
        ? `${basePath ? "." : ""}${step.fieldName}`
        : `[${step.index}]`
  }`;

  if (
    step &&
    step.type === "GetFieldStep" &&
    Object.keys(step.fieldArguments).length > 0
  ) {
    args[path] = step.fieldArguments;
  }

  return { path, args };
}
