import { ReactNode } from 'react';
import { TagsRenderer } from '../../List';

interface Connection {
  nodes: unknown[];
}

export type SelectorFunction<T> = (
  value: T,
  index: number,
  array: T[],
) => unknown;

/**
 * Creates a renderer that will loop through each `node` on the value,
 * and adds the string representations into a comma separated string.
 *
 * @param selector A function that maps each `node` to a string representation.
 */
export function createConnectionRenderer<T extends Connection>(
  selector: SelectorFunction<T['nodes'][number]>,
  renderAsTags = true,
): (val: unknown) => string | ReactNode {
  const ConnectionRenderer = (val: unknown): string | ReactNode => {
    const value = val as T;

    if (renderAsTags) {
      return TagsRenderer(value.nodes.map(selector));
    }

    return value.nodes.map(selector).join(', ');
  };

  ConnectionRenderer.displayName = 'ConnectionRenderer';
  return ConnectionRenderer;
}
