"use strict";

exports.__esModule = true;
exports.formatPieLabel = formatPieLabel;
exports.default = transformProps;

var _core = require("@superset-ui/core");

var _types = require("./types");

var _types2 = require("../types");

var _series = require("../utils/series");

var _defaults = require("../defaults");

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
const percentFormatter = (0, _core.getNumberFormatter)(_core.NumberFormats.PERCENT_2_POINT);

function formatPieLabel({
  params,
  labelType,
  numberFormatter
}) {
  const {
    name = '',
    value,
    percent
  } = params;
  const formattedValue = numberFormatter(value);
  const formattedPercent = percentFormatter(percent / 100);

  switch (labelType) {
    case _types.EchartsPieLabelType.Key:
      return name;

    case _types.EchartsPieLabelType.Value:
      return formattedValue;

    case _types.EchartsPieLabelType.Percent:
      return formattedPercent;

    case _types.EchartsPieLabelType.KeyValue:
      return `${name}: ${formattedValue}`;

    case _types.EchartsPieLabelType.KeyValuePercent:
      return `${name}: ${formattedValue} (${formattedPercent})`;

    case _types.EchartsPieLabelType.KeyPercent:
      return `${name}: ${formattedPercent}`;

    default:
      return name;
  }
}

function transformProps(chartProps) {
  const {
    formData,
    height,
    hooks,
    ownState,
    queriesData,
    width
  } = chartProps;
  const {
    data = []
  } = queriesData[0];
  const coltypeMapping = (0, _series.getColtypesMapping)(queriesData[0]);
  const {
    colorScheme,
    donut,
    groupby,
    innerRadius,
    labelsOutside,
    labelLine,
    labelType,
    legendMargin,
    legendOrientation,
    legendType,
    metric = '',
    numberFormat,
    dateFormat,
    outerRadius,
    showLabels,
    showLegend,
    showLabelsThreshold,
    emitFilter
  } = { ..._types2.DEFAULT_LEGEND_FORM_DATA,
    ..._types.DEFAULT_FORM_DATA,
    ...formData
  };
  const metricLabel = (0, _core.getMetricLabel)(metric);
  const keys = data.map(datum => (0, _series.extractGroupbyLabel)({
    datum,
    groupby,
    coltypeMapping,
    timeFormatter: (0, _core.getTimeFormatter)(dateFormat)
  }));
  const labelMap = data.reduce((acc, datum) => {
    const label = (0, _series.extractGroupbyLabel)({
      datum,
      groupby,
      coltypeMapping,
      timeFormatter: (0, _core.getTimeFormatter)(dateFormat)
    });
    return { ...acc,
      [label]: groupby.map(col => datum[col])
    };
  }, {});
  const {
    setDataMask = () => {}
  } = hooks;

  const colorFn = _core.CategoricalColorNamespace.getScale(colorScheme);

  const numberFormatter = (0, _core.getNumberFormatter)(numberFormat);
  const transformedData = data.map(datum => {
    const name = (0, _series.extractGroupbyLabel)({
      datum,
      groupby,
      coltypeMapping,
      timeFormatter: (0, _core.getTimeFormatter)(dateFormat)
    });
    return {
      value: datum[metricLabel],
      name,
      itemStyle: {
        color: colorFn(name)
      }
    };
  });
  const selectedValues = (ownState.selectedValues || []).reduce((acc, selectedValue) => {
    const index = transformedData.findIndex(({
      name
    }) => name === selectedValue);
    return { ...acc,
      [index]: selectedValue
    };
  }, {});

  const formatter = params => {
    if (params.percent && params.percent < showLabelsThreshold) return '';
    return formatPieLabel({
      params,
      numberFormatter,
      labelType
    });
  };

  const defaultLabel = {
    formatter,
    show: showLabels,
    color: '#000000'
  };
  const series = [{
    type: 'pie',
    ...(0, _series.getChartPadding)(showLegend, legendOrientation, legendMargin),
    animation: false,
    radius: [`${donut ? innerRadius : 0}%`, `${outerRadius}%`],
    center: ['50%', '50%'],
    avoidLabelOverlap: true,
    labelLine: labelsOutside && labelLine ? {
      show: true
    } : {
      show: false
    },
    label: labelsOutside ? { ...defaultLabel,
      position: 'outer',
      alignTo: 'none',
      bleedMargin: 5
    } : { ...defaultLabel,
      position: 'inner'
    },
    emphasis: {
      label: {
        show: true,
        fontWeight: 'bold',
        backgroundColor: 'white'
      }
    },
    data: transformedData
  }];
  const echartOptions = {
    grid: { ..._defaults.defaultGrid
    },
    tooltip: { ..._defaults.defaultTooltip,
      trigger: 'item',
      formatter: params => formatPieLabel({
        params,
        numberFormatter,
        labelType: _types.EchartsPieLabelType.KeyValuePercent
      })
    },
    legend: { ...(0, _series.getLegendProps)(legendType, legendOrientation, showLegend),
      data: keys
    },
    series
  };
  return {
    formData,
    width,
    height,
    echartOptions,
    setDataMask,
    emitFilter,
    labelMap,
    groupby,
    selectedValues
  };
}