function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

import React from "react";
import PropTypes from "prop-types";
import { format, scaleLinear, max, range as d3Range } from "d3";
import { startCase } from "lodash";
import { jsx, css } from "@emotion/core";
import shortid from "shortid";
import { civicFormat } from "..";
import { createColorScale, updateQuantileScale, updateEqualScale, createRange } from "../MultiLayerMap/createLayers";
var legendHeight = 65;
var legendContainer = css("\n  margin: 9px 5%;\n  display: flex;\n  align-items: baseline;\n  flex-wrap: nowrap;\n  height: ".concat(legendHeight, "px;\n  width: 90%;\n  padding-bottom: 10px;  \n"));
var colorBox = css("\n  display: flex;\n  position: relative;\n  flex-basis: 100%;\n  border: 1px solid #AAA4AB;\n  justify-content: end;\n  align-items: end;\n");
var tickNums = css("\n  position: absolute;\n  bottom: -20px;\n  right: -20px;\n  font-size: 14px;\n");
var tickNumsThreshold = css("\n  position: absolute;\n  bottom: -20px;\n  right: -7px;\n  font-size: 14px;\n");
var tickNumsOrdinal = css("\n  position: absolute;\n  bottom: -20px;\n  right: unset;\n  left: 0;\n  font-size: 14px;\n");
var tickNumsCircle = css("\n  position: absolute;\n  bottom: -25px;\n  left: 31px;\n  font-size: 14px;\n");
var barLabelStyle = css("\n  position: absolute;\n  top: -18px;\n  width: 100%;\n  text-align: center;\n  font-size: 15px;\n");
var SandboxMapLegend = React.memo(function (props) {
  var data = props.data,
      mapProps = props.mapProps;
  var civicColor = mapProps.civicColor,
      _mapProps$scaleType = mapProps.scaleType,
      scaleType = _mapProps$scaleType === void 0 ? {} : _mapProps$scaleType,
      _mapProps$dataRange = mapProps.dataRange,
      dataRange = _mapProps$dataRange === void 0 ? [] : _mapProps$dataRange,
      _mapProps$colorRange = mapProps.colorRange,
      colorRange = _mapProps$colorRange === void 0 ? [] : _mapProps$colorRange,
      fieldName = mapProps.fieldName,
      mapType = mapProps.mapType,
      layerInfo = mapProps.layerInfo,
      legend = mapProps.legend,
      multipleLayers = mapProps.multipleLayers;
  var colorScaleType = scaleType.color;
  var legendFormat = legend.format,
      legendColorRange = legend.colorRange,
      _legend$dataRange = legend.dataRange,
      legendDataRange = _legend$dataRange === void 0 ? [] : _legend$dataRange;
  var choroplethColorScale = createColorScale(civicColor, scaleType, dataRange, colorRange);

  if (colorScaleType === "equal") {
    choroplethColorScale = updateEqualScale(data, choroplethColorScale, civicColor, dataRange, colorRange, fieldName);
  }

  if (colorScaleType === "quantile") {
    choroplethColorScale = updateQuantileScale(data, choroplethColorScale, civicColor, colorRange, fieldName);
  }

  var formatColor = function formatColor(arr) {
    return arr.reduce(function (acc, cur, i) {
      return i < 3 ? "".concat(acc + cur, ",") : "".concat(acc, "1)");
    }, "rgba(");
  };

  var spColor = multipleLayers && multipleLayers[0] ? multipleLayers[0].paint["circle-color"] : "#000";
  var spColorRange = d3Range(5).map(function () {
    return spColor;
  });
  var colorScaleRange = mapType === "vtChoroplethMap" ? createRange("", legendColorRange).map(function (c) {
    return [].concat(_toConsumableArray(c), [255]);
  }) : mapType === "vtScatterPlotMap" ? createRange("", spColorRange).map(function (c) {
    return [].concat(_toConsumableArray(c), [255]);
  }) : choroplethColorScale.range()[0].length === 4 ? choroplethColorScale.range() : choroplethColorScale.range().map(function (c) {
    return [].concat(_toConsumableArray(c), [255]);
  });
  var mapColorsArr = colorScaleRange.map(function (arr) {
    return formatColor(arr);
  });
  var bins = colorScaleType === "ordinal" || colorScaleType === "threshold" ? dataRange : mapType === "vtChoroplethMap" ? legendDataRange : mapType === "vtScatterPlotMap" ? ["Less", "", "", "", "More"] : choroplethColorScale.range().map(function (d) {
    return choroplethColorScale.invertExtent(d);
  });
  var ticks = colorScaleType === "ordinal" || colorScaleType === "threshold" || mapType === "vtChoroplethMap" || mapType === "vtScatterPlotMap" ? bins : bins.reduce(function (a, c) {
    return c[1] ? [].concat(_toConsumableArray(a), [c[1]]) : [].concat(_toConsumableArray(a), [""]);
  }, []);
  var percentageFormat = format(".1%");

  var sandboxPercentFormat = function sandboxPercentFormat(p) {
    return p < 1 && p > 0 ? percentageFormat(p) : "".concat(p.toFixed(1), "%");
  };

  var sandboxDecimalFormat = format(".2n");

  var sandboxMoneyFormat = function sandboxMoneyFormat(d) {
    return "$".concat(civicFormat.numericShort(d));
  };

  var sandboxSentenceCase = function sandboxSentenceCase(str) {
    return str.length && str.split(" ").reduce(function (full, word) {
      return "".concat(full, " ").concat(word[0].toUpperCase() + word.substring(1));
    }, "").trim();
  };

  var formatTicks = function formatTicks(arr, typeFormat) {
    var formatter = mapType === "vtScatterPlotMap" ? startCase : typeFormat === "percentage" ? sandboxPercentFormat : typeFormat === "dollars" ? sandboxMoneyFormat : typeFormat === "decimal" ? sandboxDecimalFormat : typeFormat === "sentenceCase" ? sandboxSentenceCase : typeFormat === "titleCase" ? startCase : civicFormat.typeFormat || civicFormat.numeric;
    return arr.map(function (d) {
      return formatter(d);
    });
  };

  var oldLegendFormat = mapProps.tooltip && mapProps.tooltip.primary && mapProps.tooltip.primary.format;
  var formatType = legendFormat || oldLegendFormat;
  var ticksFormatted = formatTicks(ticks, formatType);
  var tickStyle = colorScaleType === "threshold" ? tickNumsThreshold : colorScaleType === "ordinal" ? tickNumsOrdinal : mapType === "vtScatterPlotMap" ? tickNumsCircle : tickNums;
  var fieldNameColor = fieldName.color;
  var colorCount = data.reduce(function (acc, d) {
    var color = choroplethColorScale(d.properties[fieldNameColor]);

    if (acc[color]) {
      acc[color]++;
    } else {
      acc[color] = {};
      acc[color] = 1;
    }

    return acc;
  }, {});
  var barScale = scaleLinear().domain([0, max(Object.values(colorCount), function (d) {
    return d;
  })]).range([0, legendHeight]);
  var barHeights = mapColorsArr.map(function (d) {
    var count = colorCount[d.slice(5, -3)];
    return mapType === "vtChoroplethMap" ? {
      h: 28,
      c: ""
    } : mapType === "vtScatterPlotMap" ? {
      h: "auto",
      c: ""
    } : count ? {
      h: barScale(count),
      c: count
    } : {
      h: 0,
      c: "0"
    };
  });
  var legendContents = mapColorsArr.map(function (d, i) {
    var borderColor = mapType === "vtScatterPlotMap" ? "transparent" : "#AAA4AB";
    var bgColor = mapType === "vtScatterPlotMap" ? "transparent" : d;
    return jsx("div", {
      key: layerInfo.displayName + shortid.generate(),
      css: colorBox,
      style: {
        borderColor: borderColor,
        backgroundColor: bgColor,
        height: "".concat(barHeights[i].h, "px")
      }
    }, jsx("div", {
      css: barLabelStyle
    }, jsx("span", null, barHeights[i].c)), jsx("div", {
      css: tickStyle
    }, jsx("span", null, ticksFormatted[i])), mapType === "vtScatterPlotMap" && jsx("div", {
      style: {
        margin: "auto",
        backgroundColor: d,
        borderRadius: "50%",
        height: "".concat(i * 8 + 10, "px"),
        width: "".concat(i * 8 + 10, "px")
      }
    }));
  });
  return jsx("div", {
    css: legendContainer
  }, legendContents);
});
SandboxMapLegend.propTypes = {
  data: PropTypes.arrayOf(PropTypes.shape({})),
  mapProps: PropTypes.shape({}).isRequired
};
SandboxMapLegend.defaultProps = {
  data: []
};
export default SandboxMapLegend;