/**
 * DevExtreme (esm/__internal/viz/m_pie_chart.js)
 * Version: 23.2.6 (build 24140-0112)
 * Build date: Sun May 19 2024
 *
 * Copyright (c) 2012 - 2024 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
import registerComponent from "../../core/component_registrator";
import {
    noop as _noop
} from "../../core/utils/common";
import {
    extend as _extend
} from "../../core/utils/extend";
import {
    each as _each
} from "../../core/utils/iterator";
import {
    isNumeric
} from "../../core/utils/type";
import consts from "../../viz/components/consts";
import {
    plugins as annotationsPlugins
} from "../../viz/core/annotations";
import {
    plugins as centerTemplatePlugins
} from "../../viz/core/center_template";
import {
    getVerticallyShiftedAngularCoords as _getVerticallyShiftedAngularCoords,
    normalizeAngle
} from "../../viz/core/utils";
import {
    Range
} from "../../viz/translators/range";
import {
    Translator1D
} from "../../viz/translators/translator1d";
import {
    BaseChart,
    overlapping
} from "./chart_components/m_base_chart";
var {
    states: states
} = consts;
var seriesSpacing = consts.pieSeriesSpacing;
var OPTIONS_FOR_REFRESH_SERIES = ["startAngle", "innerRadius", "segmentsDirection", "type"];
var NORMAL_STATE = states.normalMark;
var HOVER_STATE = states.hoverMark;
var SELECTED_STATE = states.selectedMark;
var MAX_RESOLVE_ITERATION_COUNT = 5;
var LEGEND_ACTIONS = [states.resetItem, states.applyHover, states.applySelected, states.applySelected];

function shiftInColumnFunction(box, length) {
    return {
        x: box.x,
        y: box.y - length
    }
}

function dividePoints(series, points) {
    return series.getVisiblePoints().reduce((r, point) => {
        var angle = normalizeAngle(point.middleAngle);
        (angle <= 90 || angle >= 270 ? r.right : r.left).push(point);
        return r
    }, points || {
        left: [],
        right: []
    })
}

function resolveOverlappedLabels(points, shiftCallback, inverseDirection, canvas) {
    var overlapped;
    if (inverseDirection) {
        points.left.reverse();
        points.right.reverse()
    }
    overlapped = overlapping.resolveLabelOverlappingInOneDirection(points.left, canvas, false, false, shiftCallback);
    return overlapping.resolveLabelOverlappingInOneDirection(points.right, canvas, false, false, shiftCallback) || overlapped
}

function getLegendItemAction(points) {
    var state = NORMAL_STATE;
    points.forEach(point => {
        var _a;
        var seriesOptions = null === (_a = point.series) || void 0 === _a ? void 0 : _a.getOptions();
        var pointState = point.fullState;
        if ("none" === (null === seriesOptions || void 0 === seriesOptions ? void 0 : seriesOptions.hoverMode)) {
            pointState &= ~HOVER_STATE
        }
        if ("none" === (null === seriesOptions || void 0 === seriesOptions ? void 0 : seriesOptions.selectionMode)) {
            pointState &= ~SELECTED_STATE
        }
        state |= pointState
    });
    return LEGEND_ACTIONS[state]
}

function correctPercentValue(value) {
    if (isNumeric(value)) {
        if (value > 1) {
            value = 1
        } else if (value < 0) {
            value = 0
        }
    } else {
        value = void 0
    }
    return value
}
var pieSizeEqualizer = function() {
    function removeFromList(list, item) {
        return list.filter(li => li !== item)
    }
    var pies = [];
    var timers = {};
    return {
        queue(pie) {
            var group = pie.getSizeGroup();
            pies = (list = pies, item = pie, removeFromList(list, item).concat(item));
            var list, item;
            clearTimeout(timers[group]);
            timers[group] = setTimeout(() => {
                ! function(group, allPies) {
                    var pies = allPies.filter(p => p._isVisible() && p.getSizeGroup() === group);
                    var minRadius = Math.min.apply(null, pies.map(p => p.getSizeGroupLayout().radius));
                    var minPie = pies.filter(p => p.getSizeGroupLayout().radius === minRadius);
                    pies.forEach(p => p.render({
                        force: true,
                        sizeGroupLayout: minPie.length ? minPie[0].getSizeGroupLayout() : {}
                    }))
                }(group, pies)
            })
        },
        remove(pie) {
            pies = removeFromList(pies, pie);
            if (!pies.length) {
                timers = {}
            }
        }
    }
}();
var dxPieChart = BaseChart.inherit({
    _themeSection: "pie",
    _layoutManagerOptions() {
        return _extend(true, {}, this.callBase(), {
            piePercentage: correctPercentValue(this._themeManager.getOptions("diameter")),
            minPiePercentage: correctPercentValue(this._themeManager.getOptions("minDiameter"))
        })
    },
    _optionChangesMap: {
        diameter: "REINIT",
        minDiameter: "REINIT",
        sizeGroup: "REINIT"
    },
    _disposeCore() {
        pieSizeEqualizer.remove(this);
        this.callBase()
    },
    _groupSeries() {
        var _a;
        var {
            series: series
        } = this;
        this._groupsData = {
            groups: [{
                series: series,
                valueOptions: {
                    valueType: "numeric"
                }
            }],
            argumentOptions: null === (_a = series[0]) || void 0 === _a ? void 0 : _a.getOptions()
        }
    },
    getArgumentAxis: () => null,
    _getValueAxis() {
        var translator = (new Translator1D).setCodomain(360, 0);
        return {
            getTranslator: () => translator,
            setBusinessRange(range) {
                translator.setDomain(range.min, range.max)
            }
        }
    },
    _populateBusinessRange() {
        this.series.map(series => {
            var range = new Range;
            range.addRange(series.getRangeData().val);
            series.getValueAxis().setBusinessRange(range);
            return range
        })
    },
    _specialProcessSeries() {
        _each(this.series, (_, singleSeries) => {
            singleSeries.arrangePoints()
        })
    },
    _checkPaneName: () => true,
    _processSingleSeries(singleSeries) {
        this.callBase(singleSeries);
        singleSeries.arrangePoints()
    },
    _handleSeriesDataUpdated() {
        var maxPointCount = 0;
        this.series.forEach(s => {
            maxPointCount = Math.max(s.getPointsCount(), maxPointCount)
        });
        this.series.forEach(s => {
            s.setMaxPointsCount(maxPointCount)
        });
        this.callBase()
    },
    _getLegendOptions(item) {
        var legendItem = this.callBase(item);
        var {
            legendData: legendData
        } = legendItem;
        legendData.argument = item.argument;
        legendData.argumentIndex = item.argumentIndex;
        legendData.points = [item];
        return legendItem
    },
    _getLegendTargets() {
        var itemsByArgument = {};
        (this.series || []).forEach(series => {
            series.getPoints().forEach(point => {
                var argument = point.argument.valueOf();
                var index = series.getPointsByArg(argument).indexOf(point);
                var key = argument.valueOf().toString() + index;
                itemsByArgument[key] = itemsByArgument[key] || [];
                var argumentCount = itemsByArgument[key].push(point);
                point.index = itemsByArgument[key][argumentCount - 2] ? itemsByArgument[key][argumentCount - 2].index : Object.keys(itemsByArgument).length - 1;
                point.argumentIndex = index
            })
        });
        var items = [];
        _each(itemsByArgument, (_, points) => {
            points.forEach((point, index) => {
                if (0 === index) {
                    items.push(this._getLegendOptions(point));
                    return
                }
                var item = items[items.length - 1];
                item.legendData.points.push(point);
                if (!item.visible) {
                    item.visible = point.isVisible()
                }
            })
        });
        return items
    },
    _getLayoutTargets() {
        return [{
            canvas: this._canvas
        }]
    },
    _getLayoutSeries(series, drawOptions) {
        var layout;
        var canvas = this._canvas;
        var drawnLabels = false;
        layout = this.layoutManager.applyPieChartSeriesLayout(canvas, series, true);
        series.forEach(singleSeries => {
            singleSeries.correctPosition(layout, canvas);
            drawnLabels = singleSeries.drawLabelsWOPoints() || drawnLabels
        });
        if (drawnLabels) {
            layout = this.layoutManager.applyPieChartSeriesLayout(canvas, series, drawOptions.hideLayoutLabels)
        }
        series.forEach(singleSeries => {
            singleSeries.hideLabels()
        });
        this._sizeGroupLayout = {
            x: layout.centerX,
            y: layout.centerY,
            radius: layout.radiusOuter,
            drawOptions: drawOptions
        };
        return layout
    },
    _getLayoutSeriesForEqualPies(series, sizeGroupLayout) {
        var canvas = this._canvas;
        var layout = this.layoutManager.applyEqualPieChartLayout(series, sizeGroupLayout);
        series.forEach(s => {
            s.correctPosition(layout, canvas);
            s.drawLabelsWOPoints()
        });
        this.layoutManager.correctPieLabelRadius(series, layout, canvas);
        return layout
    },
    _updateSeriesDimensions(drawOptions) {
        var visibleSeries = this._getVisibleSeries();
        var lengthVisibleSeries = visibleSeries.length;
        var innerRad;
        var delta;
        var layout;
        var {
            sizeGroupLayout: sizeGroupLayout
        } = drawOptions;
        if (lengthVisibleSeries) {
            layout = sizeGroupLayout ? this._getLayoutSeriesForEqualPies(visibleSeries, sizeGroupLayout) : this._getLayoutSeries(visibleSeries, drawOptions);
            delta = (layout.radiusOuter - layout.radiusInner - seriesSpacing * (lengthVisibleSeries - 1)) / lengthVisibleSeries;
            innerRad = layout.radiusInner;
            this._setGeometry(layout);
            visibleSeries.forEach(singleSeries => {
                singleSeries.correctRadius({
                    radiusInner: innerRad,
                    radiusOuter: innerRad + delta
                });
                innerRad += delta + seriesSpacing
            })
        }
    },
    _renderSeries(drawOptions, isRotated, isLegendInside) {
        this._calculateSeriesLayout(drawOptions, isRotated);
        if (!drawOptions.sizeGroupLayout && this.getSizeGroup()) {
            pieSizeEqualizer.queue(this);
            this._clearCanvas();
            return
        }
        this._renderSeriesElements(drawOptions, isLegendInside)
    },
    _getCenter() {
        return this._center
    },
    getInnerRadius() {
        return this._innerRadius
    },
    _getLegendCallBack() {
        var legend = this._legend;
        var items = this._getLegendTargets().map(i => i.legendData);
        return target => {
            items.forEach(data => {
                var points = [];
                var callback = legend.getActionCallback({
                    index: data.id
                });
                this.series.forEach(series => {
                    var seriesPoints = series.getPointsByKeys(data.argument, data.argumentIndex);
                    points.push.apply(points, seriesPoints)
                });
                if (target && target.argument === data.argument && target.argumentIndex === data.argumentIndex) {
                    points.push(target)
                }
                callback(getLegendItemAction(points))
            })
        }
    },
    _locateLabels(resolveLabelOverlapping) {
        var iterationCount = 0;
        var labelsWereOverlapped;
        var wordWrapApplied;
        do {
            wordWrapApplied = this._adjustSeriesLabels("shift" === resolveLabelOverlapping);
            labelsWereOverlapped = this._resolveLabelOverlapping(resolveLabelOverlapping)
        } while ((labelsWereOverlapped || wordWrapApplied) && ++iterationCount < MAX_RESOLVE_ITERATION_COUNT)
    },
    _adjustSeriesLabels(moveLabelsFromCenter) {
        return this.series.reduce((r, s) => s.adjustLabels(moveLabelsFromCenter) || r, false)
    },
    _applyExtraSettings: _noop,
    _resolveLabelOverlappingShift() {
        var inverseDirection = "anticlockwise" === this.option("segmentsDirection");
        var seriesByPosition = this.series.reduce((r, s) => {
            (r[s.getOptions().label.position] || r.outside).push(s);
            return r
        }, {
            inside: [],
            columns: [],
            outside: []
        });
        var labelsOverlapped = false;
        if (seriesByPosition.inside.length > 0) {
            var pointsToResolve = seriesByPosition.inside.reduce((r, singleSeries) => {
                var visiblePoints = singleSeries.getVisiblePoints();
                return visiblePoints.reduce((r, point) => {
                    r.left.push(point);
                    return r
                }, r)
            }, {
                left: [],
                right: []
            });
            labelsOverlapped = resolveOverlappedLabels(pointsToResolve, shiftInColumnFunction, inverseDirection, this._canvas) || labelsOverlapped
        }
        labelsOverlapped = seriesByPosition.columns.reduce((r, singleSeries) => resolveOverlappedLabels(dividePoints(singleSeries), shiftInColumnFunction, inverseDirection, this._canvas) || r, labelsOverlapped);
        if (seriesByPosition.outside.length > 0) {
            labelsOverlapped = resolveOverlappedLabels(seriesByPosition.outside.reduce((r, singleSeries) => dividePoints(singleSeries, r), null), (box, length) => _getVerticallyShiftedAngularCoords(box, -length, this._center), inverseDirection, this._canvas) || labelsOverlapped
        }
        return labelsOverlapped
    },
    _setGeometry(_ref) {
        var {
            centerX: x,
            centerY: y,
            radiusInner: radiusInner
        } = _ref;
        this._center = {
            x: x,
            y: y
        };
        this._innerRadius = radiusInner
    },
    _disposeSeries() {
        this.callBase.apply(this, arguments);
        this._abstractSeries = null
    },
    _legendDataField: "point",
    _legendItemTextField: "argument",
    _applyPointMarkersAutoHiding: _noop,
    _renderTrackers: _noop,
    _trackerType: "PieTracker",
    _createScrollBar: _noop,
    _updateAxesLayout: _noop,
    _applyClipRects: _noop,
    _appendAdditionalSeriesGroups: _noop,
    _prepareToRender: _noop,
    _isLegendInside: _noop,
    _renderAxes: _noop,
    _shrinkAxes: _noop,
    _isRotated: _noop,
    _seriesPopulatedHandlerCore: _noop,
    _reinitAxes: _noop,
    _correctAxes: _noop,
    _getExtraOptions() {
        return {
            startAngle: this.option("startAngle"),
            innerRadius: this.option("innerRadius"),
            segmentsDirection: this.option("segmentsDirection"),
            type: this.option("type")
        }
    },
    getSizeGroup() {
        return this._themeManager.getOptions("sizeGroup")
    },
    getSizeGroupLayout() {
        return this._sizeGroupLayout || {}
    }
});
_each(OPTIONS_FOR_REFRESH_SERIES, (_, name) => {
    dxPieChart.prototype._optionChangesMap[name] = "REFRESH_SERIES_DATA_INIT"
});
dxPieChart.addPlugin(centerTemplatePlugins.pieChart);
dxPieChart.addPlugin(annotationsPlugins.core);
dxPieChart.addPlugin(annotationsPlugins.pieChart);
registerComponent("dxPieChart", dxPieChart);
export default dxPieChart;
