import { scaleLinear, scaleRadial } from 'd3-scale';
import min from './min';
import max from './max';
const scatter = function scatter(opts) {
  const {
    dataset,
    config,
    isDesktop = false
  } = opts;
  if (!dataset || !config) return undefined;
  const {
    x: xAttr,
    y: yAttr,
    size: sizeAttr,
    alpha: alphaAttr,
    color: colorAttr
  } = config;
  let xMin;
  let xMax;
  let yMin;
  let yMax;
  let rMin;
  let rMax;
  let alphaMin;
  let alphaMax;
  const getVal = (d, attr, fallback) => {
    if (!attr) return fallback;
    if (typeof attr === 'string') return d[attr];
    return attr;
  };
  const data = dataset.map(d => {
    const xVal = d[xAttr];
    const yVal = d[yAttr];
    const rVal = getVal(d, sizeAttr, 5);
    const alpha = getVal(d, alphaAttr, 1);
    xMin = min(xMin, xVal);
    xMax = max(xMax, xVal);
    yMin = min(yMin, yVal);
    yMax = max(yMax, yVal);
    rMin = min(rMin, rVal);
    rMax = max(rMax, rVal);
    alphaMin = min(alphaMin, alpha);
    alphaMax = max(alphaMax, alpha);
    const datapoint = {
      x: xVal,
      y: yVal,
      r: rVal,
      alpha,
      color: colorAttr && (d[colorAttr] || colorAttr)
    };
    return datapoint;
  });
  const {
    xmin = xMin,
    xmax = xMax,
    ymin = yMin,
    ymax = yMax
  } = config;
  const x = scaleLinear([xmin, xmax], [0, 1]).nice();
  const y = scaleLinear([ymin, ymax], [1, 0]).nice();
  const bigR = isDesktop ? 20 : 10;
  const r = scaleRadial([rMin, rMax], rMin === rMax ? [rMax, rMax] : [1, bigR]);
  const alphaRange = (() => {
    if (alphaMin < 0 || alphaMax > 1) return [0.2, 1];
    return [alphaMin, alphaMax];
  })();
  const alpha = scaleLinear([alphaMin, alphaMax], alphaRange);
  return {
    data,
    scales: {
      x,
      y,
      r,
      alpha
    },
    config
  };
};
export default scatter;