"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _propTypes = _interopRequireDefault(require("prop-types"));

var _d = require("d3");

var _lodash = require("lodash");

var _core = require("@emotion/core");

var _shortid = _interopRequireDefault(require("shortid"));

var _civicFormat = _interopRequireDefault(require("../utils/civicFormat"));

var _createLayers = require("../MultiLayerMap/createLayers");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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; } }

var legendHeight = 65;
var legendContainer = (0, _core.css)("\n  margin: 0.5rem 5% 1rem 5%;\n  display: flex;\n  align-items: end;\n  flex-wrap: nowrap;\n  height: ".concat(legendHeight, "px;\n  width: 90%;\n"));
var colorBox = (0, _core.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 = (0, _core.css)("\n  position: absolute;\n  bottom: -20px;\n  right: 0;\n  font-size: 14px;\n");
var tickNumsThreshold = (0, _core.css)("\n  position: absolute;\n  bottom: -20px;\n  right: -7px;\n  font-size: 14px;\n");
var tickNumsOrdinal = (0, _core.css)("\n  position: absolute;\n  bottom: -20px;\n  right: unset;\n  left: 0;\n  font-size: 14px;\n");
var barLabelStyle = (0, _core.css)("\n  position: absolute;\n  top: -18px;\n  width: 100%;\n  text-align: center;\n  font-size: 15px;\n");

var SandboxMapLegend = function SandboxMapLegend(props) {
  var data = props.data,
      mapProps = props.mapProps;
  var civicColor = mapProps.civicColor,
      scaleType = mapProps.scaleType,
      dataRange = mapProps.dataRange,
      colorRange = mapProps.colorRange,
      fieldName = mapProps.fieldName;
  var colorScaleType = scaleType.color;
  var choroplethColorScale = (0, _createLayers.createColorScale)(civicColor, scaleType, dataRange, colorRange);

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

  if (colorScaleType === "quantile") {
    choroplethColorScale = (0, _createLayers.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 colorScaleRange = 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 : choroplethColorScale.range().map(function (d) {
    return choroplethColorScale.invertExtent(d);
  });
  var ticks = colorScaleType === "ordinal" || colorScaleType === "threshold" ? bins : bins.reduce(function (a, c) {
    return c[1] ? [].concat(_toConsumableArray(a), [c[1]]) : [].concat(_toConsumableArray(a), [""]);
  }, []);
  var percentageFormat = (0, _d.format)(".1%");

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

  var sandboxDecimalFormat = (0, _d.format)(".2n");

  var sandboxMoneyFormat = function sandboxMoneyFormat(d) {
    return "$".concat(_civicFormat["default"].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 = typeFormat === "numeric" ? _civicFormat["default"].numeric : typeFormat === "numericShort" ? _civicFormat["default"].numericShort : typeFormat === "decimal" ? sandboxDecimalFormat : typeFormat === "percent" ? sandboxPercentFormat : typeFormat === "dollars" ? sandboxMoneyFormat : typeFormat === "year" ? _civicFormat["default"].year : typeFormat === "monthYear" ? _civicFormat["default"].monthYear : typeFormat === "titleCase" ? _lodash.startCase : typeFormat === "sentenceCase" ? sandboxSentenceCase : _civicFormat["default"].unformatted;
    return arr.map(function (d) {
      return formatter(d);
    });
  };

  var formatType = mapProps.tooltip && mapProps.tooltip.primary && mapProps.tooltip.primary.format ? mapProps.tooltip.primary.format : "numeric";
  var ticksFormatted = formatTicks(ticks, formatType);
  var tickStyle = colorScaleType === "threshold" ? tickNumsThreshold : colorScaleType === "ordinal" ? tickNumsOrdinal : 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 = (0, _d.scaleLinear)().domain([0, (0, _d.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 count ? {
      h: barScale(count),
      c: count
    } : {
      h: 0,
      c: ""
    };
  });
  var legend = mapColorsArr.map(function (d, i) {
    return (0, _core.jsx)("div", {
      key: _shortid["default"].generate(),
      css: colorBox,
      style: {
        backgroundColor: d,
        height: "".concat(barHeights[i].h, "px")
      }
    }, (0, _core.jsx)("div", {
      css: barLabelStyle
    }, (0, _core.jsx)("span", null, barHeights[i].c)), (0, _core.jsx)("div", {
      css: tickStyle
    }, (0, _core.jsx)("span", null, ticksFormatted[i])));
  });
  return (0, _core.jsx)("div", {
    css: legendContainer
  }, legend);
};

SandboxMapLegend.propTypes = {
  data: _propTypes["default"].arrayOf(_propTypes["default"].shape({})).isRequired,
  mapProps: _propTypes["default"].shape({}).isRequired
};
var _default = SandboxMapLegend;
exports["default"] = _default;