import * as echarts from "echarts"

export function createChart(element) {
  return echarts.init(element)
}

export function buildChartOption(chartType, display, payload) {
  const safeDisplay = display || {}
  const dimensions = (payload && payload.dimensions) || []
  const sourceSeries = (payload && payload.series) || []
  const labels = dimensions.map(item => item.label)

  if (chartType === "pie") {
    const values = sourceSeries.length ? sourceSeries[0].values : []
    return {
      tooltip: { trigger: "item" },
      legend: { show: safeDisplay.showLegend !== false },
      series: [{
        type: "pie",
        radius: safeDisplay.donut ? ["45%", "70%"] : "70%",
        label: { show: safeDisplay.showLabel !== false },
        data: labels.map((name, index) => ({
          name,
          value: values[index] == null ? 0 : values[index]
        }))
      }]
    }
  }

  const horizontal = chartType === "bar" && safeDisplay.horizontal
  const series = sourceSeries.map(item => ({
    name: item.name,
    type: chartType === "bar" ? "bar" : "line",
    smooth: chartType === "line" && Boolean(safeDisplay.smooth),
    stack: chartType === "bar" && safeDisplay.stacked ? "total" : undefined,
    areaStyle: chartType === "line" && safeDisplay.area ? {} : undefined,
    data: item.values || []
  }))

  return {
    tooltip: { trigger: "axis" },
    legend: { show: safeDisplay.showLegend !== false },
    xAxis: horizontal
      ? { type: "value" }
      : { type: "category", data: labels },
    yAxis: horizontal
      ? { type: "category", data: labels }
      : { type: "value" },
    series
  }
}

export function hasChartData(payload) {
  return Boolean(payload && (
    (payload.summary && payload.summary.value !== null && payload.summary.value !== undefined)
    || (payload.dimensions && payload.dimensions.length)
  ))
}
