import { h } from "@stencil/core";
/**
 * Displays a cartesian product of the input props
 *
 * @returns
 */
export function MatrixStory({ matrix, props, Component, }) {
  const propMatrix = Object.keys(matrix).map((propKey) => {
    const propValues = matrix[propKey];
    return propValues.map((val) => {
      return {
        [propKey]: val,
      };
    });
  });
  const combinations = cartesian(...propMatrix);
  const propsCombinations = combinations.map((combo) => {
    return combo.reduce((props, prop) => {
      return {
        ...props,
        ...prop,
      };
    }, {});
  });
  return propsCombinations.map((combo) => {
    const example = { ...props, ...combo };
    return (h("div", null,
      h(PropsTable, { values: example }),
      h("hr", null),
      " ",
      h("br", null),
      h(Component, Object.assign({}, example)),
      h("br", null)));
  });
}
function PropsTable({ values }) {
  return (h("table", null,
    h("tbody", null, Object.keys(values).map((key) => {
      return (h("tr", null,
        h("th", null, key),
        h("td", null, JSON.stringify(values[key]))));
    }))));
}
/**
 * Source: https://stackoverflow.com/questions/15298912/javascript-generating-combinations-from-n-arrays-with-m-elements
 *
 * TODO: Could replace with a fork of https://www.npmjs.com/package/cartesian
 *
 * @param args - an array of arrays
 * @returns combinations of the elements in those array
 */
function cartesian(...args) {
  var r = [], max = args.length - 1;
  function helper(arr, i) {
    for (var j = 0, l = args[i].length; j < l; j++) {
      var a = arr.slice(0); // clone arr
      a.push(args[i][j]);
      if (i == max)
        r.push(a);
      else
        helper(a, i + 1);
    }
  }
  helper([], 0);
  return r;
}
