'use strict';

var index = require('../KitStoreProvider/index.js');
var LineChartLegend = require('./LineChartLegend.js');
var styled = require('./styled.js');
var TooltipFormatter = require('./TooltipFormatter.js');
var type = require('./type.js');
var utils = require('./utils.js');
var useParrotTranslation = require('../../hooks/useParrotTranslation.js');
var antd = require('antd');
var cs = require('classnames');
var dayjs = require('dayjs');
var React = require('react');
var recharts = require('recharts');
var LineChartToolBar = require('./LineChartToolBar.js');
var chart = require('../../store/chart.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var cs__default = /*#__PURE__*/_interopDefault(cs);
var dayjs__default = /*#__PURE__*/_interopDefault(dayjs);
var React__default = /*#__PURE__*/_interopDefault(React);

var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
const RenderChart = (props) => {
  const {
    metricName,
    showLegend,
    syncId,
    showXAxis,
    yAxisAlign,
    height,
    type: type$1,
    mode = "legend",
    dropdownProps,
    onLabelsChange,
    metric,
    yAxisProps,
    xAxisProps,
    actionsProps,
    tooltipProps,
    width,
    dateRange = [dayjs__default.default(), dayjs__default.default()],
    emptyText,
    emptyIcon
  } = props;
  const { t } = useParrotTranslation();
  const dispatch = index.useKitDispatch();
  const [deselected, setDeselected] = React.useState([]);
  const [hovering, setHovering] = React.useState([]);
  const [hoveringSelf, setHoveringSelf] = React.useState([]);
  const [tempDeselected, setTempDeselected] = React.useState([]);
  const streams = React.useMemo(() => metric.sample_streams, [metric]);
  const legends = React.useMemo(() => {
    return metric.sample_streams.map((stream) => stream.legend);
  }, [metric.sample_streams]);
  const areaChartData = React.useMemo(
    () => utils.convertLineChartDataStruct(streams.map((stream) => stream.points)),
    [streams]
  );
  const yDomain = utils.getYAxisDomain(areaChartData, type$1, metric.unit);
  const xDomain = utils.getLineChartXAxisDomain(dateRange, dateRange[1].valueOf());
  const xTicks = utils.lineChartXaxisCal(xDomain[1], dateRange, width);
  const onLegendClick = React.useCallback(
    (id) => {
      setDeselected((prev) => {
        var _a;
        const currentDeselected = tempDeselected.length ? tempDeselected : prev;
        if (currentDeselected.length === 0) {
          return streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id);
        }
        if (currentDeselected.length === streams.length - 1) {
          const highlightedId = (_a = streams.find(
            (stream) => !currentDeselected.includes(stream.legend.id)
          )) == null ? void 0 : _a.legend.id;
          if (id === highlightedId) {
            return [];
          } else {
            return currentDeselected.filter(
              (deselectedId) => deselectedId !== id
            );
          }
        }
        const isHighlighted = !currentDeselected.includes(id);
        if (isHighlighted) {
          return [...currentDeselected, id];
        } else {
          return currentDeselected.filter(
            (deselectedId) => deselectedId !== id
          );
        }
      });
      if (tempDeselected.length) {
        setTempDeselected([]);
      }
    },
    [streams, tempDeselected]
  );
  const onLegendHover = React.useCallback(
    (method, id) => {
      if (method === "enter") {
        if (deselected.length) {
          setTempDeselected(deselected);
          if (deselected.includes(id)) {
            setDeselected(
              streams.map((stream) => stream.legend.id).filter(
                (legendId) => legendId !== id && deselected.includes(legendId)
              )
            );
            setHovering(
              streams.map((stream) => stream.legend.id).filter((legendId) => legendId === id)
            );
            setHoveringSelf(
              streams.map((stream) => stream.legend.id).filter((legendId) => legendId === id)
            );
          } else {
            if (deselected.length === streams.length - 1) {
              setDeselected([]);
              setHovering(
                streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id)
              );
            } else {
              setHovering(
                streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id)
              );
              setHoveringSelf(
                streams.map((stream) => stream.legend.id).filter(
                  (legendId) => legendId !== id && !deselected.includes(legendId)
                )
              );
            }
          }
        } else {
          setHovering(
            streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id)
          );
        }
      } else {
        if (tempDeselected.length) {
          setDeselected(tempDeselected);
          setTempDeselected([]);
        }
        setHovering([]);
        setHoveringSelf([]);
      }
    },
    [deselected, streams, tempDeselected]
  );
  const hidePointer = React.useCallback(() => {
    dispatch({
      type: chart.ChartActions.SET_POINTER,
      payload: { visible: false, uuid: syncId }
    });
  }, [dispatch, syncId]);
  const handleMouseMove = React.useCallback(
    (e) => {
      var _a;
      if (e.isTooltipActive) {
        const { chartX, activePayload } = e;
        if (!((_a = activePayload == null ? void 0 : activePayload[0]) == null ? void 0 : _a.payload)) {
          return;
        }
        dispatch({
          type: chart.ChartActions.SET_POINTER,
          payload: {
            uuid: syncId,
            visible: true,
            left: chartX,
            text: dayjs__default.default(Number(activePayload[0].payload.t)).format(
              "MM/DD HH:mm:ss"
            ),
            value: activePayload[0].payload.v
          }
        });
      }
    },
    [dispatch, syncId]
  );
  if (!(streams == null ? void 0 : streams.length) || streams.every((stream) => {
    var _a;
    return !((_a = stream.points) == null ? void 0 : _a.length);
  })) {
    return /* @__PURE__ */ React__default.default.createElement("div", { className: styled.MetricLegendTabStyle }, /* @__PURE__ */ React__default.default.createElement("div", { className: "name-toolbar" }, /* @__PURE__ */ React__default.default.createElement(
      LineChartLegend.default,
      {
        streams,
        metricName,
        deselected,
        hovering,
        hovereringSelf: hoveringSelf,
        onClick: onLegendClick,
        onHover: onLegendHover,
        legends
      }
    )), /* @__PURE__ */ React__default.default.createElement("div", { className: cs__default.default("content", mode === "single" && "single-content") }, /* @__PURE__ */ React__default.default.createElement(
      antd.Empty,
      {
        description: emptyText || t("metric.empty"),
        image: emptyIcon ? emptyIcon : null,
        imageStyle: emptyIcon ? {} : { display: "none" }
      }
    )));
  }
  return /* @__PURE__ */ React__default.default.createElement(React__default.default.Fragment, null, /* @__PURE__ */ React__default.default.createElement(
    LineChartToolBar,
    {
      showLegend,
      streams,
      metricName,
      deselected,
      hovering,
      hoveringSelf,
      onLegendClick,
      legends,
      actionsProps,
      dropdownProps,
      onLegendHover
    }
  ), /* @__PURE__ */ React__default.default.createElement(recharts.ResponsiveContainer, { height }, /* @__PURE__ */ React__default.default.createElement(
    recharts.AreaChart,
    {
      style: { backgroundColor: "white" },
      margin: showLegend ? { top: 10, left: -20, right: 0, bottom: 0 } : { top: 20, left: -20, right: 0, bottom: 5 },
      data: areaChartData,
      syncId,
      onMouseLeave: hidePointer,
      onMouseMove: handleMouseMove
    },
    /* @__PURE__ */ React__default.default.createElement(
      recharts.XAxis,
      __spreadValues({
        hide: !showXAxis,
        dataKey: "t",
        axisLine: false,
        tickLine: false,
        type: "number",
        ticks: xTicks,
        domain: xDomain,
        tickFormatter: (tick) => utils.lineChartTickFormatter(tick, dateRange)
      }, xAxisProps)
    ),
    /* @__PURE__ */ React__default.default.createElement(
      recharts.YAxis,
      __spreadValues({
        width: 200,
        mirror: true,
        axisLine: false,
        tickLine: false,
        allowDecimals: false,
        domain: yDomain,
        orientation: yAxisAlign,
        tick: {
          dx: 20,
          dy: 16,
          fontSize: 12
        },
        ticks: [yDomain[1] / 2, yDomain[1]],
        tickFormatter: (tick) => utils.lineChartYaxisTickFormatter(tick, metric.unit)
      }, yAxisProps)
    ),
    /* @__PURE__ */ React__default.default.createElement(
      recharts.Tooltip,
      __spreadValues({
        wrapperStyle: { left: 20 },
        content: tooltipProps.format && /* @__PURE__ */ React__default.default.createElement(
          TooltipFormatter,
          {
            deselected,
            legends,
            format: tooltipProps.format
          }
        )
      }, tooltipProps)
    ),
    streams.map((item, index) => {
      if (deselected.includes(item.legend.id)) {
        return null;
      }
      return /* @__PURE__ */ React__default.default.createElement(
        recharts.Area,
        {
          key: index,
          dataKey: `v${index}`,
          stackId: type$1 === type.ILineChartGraphType.Stack ? "stack" : void 0,
          stroke: item.legend.stroke ? `${item.legend.color}1A` : item.legend.color,
          fill: item.legend.fill,
          isAnimationActive: false,
          activeDot: {
            stroke: item.legend.color,
            r: 4,
            strokeWidth: 2,
            fill: "white"
          },
          opacity: hovering.includes(item.legend.id) ? 0.3 : 1
        }
      );
    })
  )));
};
var RenderChart$1 = RenderChart;

module.exports = RenderChart$1;
