function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _assert_this_initialized(self) {
    if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return self;
}
function _call_super(_this, derived, args) {
    derived = _get_prototype_of(derived);
    return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
}
function _class_call_check(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
function _defineProperties(target, props) {
    for(var i = 0; i < props.length; i++){
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
function _get(target, property, receiver) {
    if (typeof Reflect !== "undefined" && Reflect.get) {
        _get = Reflect.get;
    } else {
        _get = function get(target, property, receiver) {
            var base = _super_prop_base(target, property);
            if (!base) return;
            var desc = Object.getOwnPropertyDescriptor(base, property);
            if (desc.get) {
                return desc.get.call(receiver || target);
            }
            return desc.value;
        };
    }
    return _get(target, property, receiver || target);
}
function _get_prototype_of(o) {
    _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
    };
    return _get_prototype_of(o);
}
function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            writable: true,
            configurable: true
        }
    });
    if (superClass) _set_prototype_of(subClass, superClass);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _possible_constructor_return(self, call) {
    if (call && (_type_of(call) === "object" || typeof call === "function")) {
        return call;
    }
    return _assert_this_initialized(self);
}
function _set_prototype_of(o, p) {
    _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
        o.__proto__ = p;
        return o;
    };
    return _set_prototype_of(o, p);
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _super_prop_base(object, property) {
    while(!Object.prototype.hasOwnProperty.call(object, property)){
        object = _get_prototype_of(object);
        if (object === null) break;
    }
    return object;
}
function _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _is_native_reflect_construct() {
    try {
        var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
    } catch (_) {}
    return (_is_native_reflect_construct = function() {
        return !!result;
    })();
}
import { groups, min, max, sum } from "d3-array";
import { pointer } from "d3-selection";
import { colorContrast } from "@d3plus/color";
import { merge } from "@d3plus/data";
import { assign, backgroundColor, elem } from "@d3plus/dom";
import { accessor, configPrep, constant } from "../utils/index.js";
import { Circle, Path, Rect } from "../shapes/index.js";
import Viz from "./Viz.js";
var tau = Math.PI * 2;
var Radar = /*#__PURE__*/ function(Viz) {
    "use strict";
    _inherits(Radar, Viz);
    function Radar() {
        _class_call_check(this, Radar);
        var _this;
        _this = _call_super(this, Radar);
        _this._axisConfig = {
            shapeConfig: {
                fill: constant("none"),
                labelConfig: {
                    fontColor: function fontColor() {
                        var bg = _this._select ? backgroundColor(_this._select.node()) : "rgb(255, 255, 255)";
                        return colorContrast(bg);
                    },
                    padding: 0,
                    textAnchor: function textAnchor(d, i, x) {
                        return x.textAnchor;
                    },
                    verticalAlign: "middle"
                },
                stroke: function stroke() {
                    var bg = _this._select ? backgroundColor(_this._select.node()) : "rgb(255, 255, 255)";
                    return colorContrast(bg);
                },
                strokeWidth: constant(1)
            }
        };
        _this._discrete = "metric";
        _this._levels = 6;
        _this._metric = accessor("metric");
        _this._outerPadding = 100;
        _this._shape = constant("Path");
        _this._value = accessor("value");
        return _this;
    }
    _create_class(Radar, [
        {
            /**
      Extends the draw behavior of the abstract Viz class.
      @private
*/ key: "_draw",
            value: function _draw(callback) {
                var _loop = function(e) {
                    var event = events[e];
                    pathConfig.on[event] = function(d, i, s, e) {
                        var x = d.points.map(function(p) {
                            return p.x + width / 2;
                        });
                        var y = d.points.map(function(p) {
                            return p.y + height / 2;
                        });
                        var cursor = pointer(e, _this._select.node());
                        var xDist = x.map(function(p) {
                            return Math.abs(p - cursor[0]);
                        });
                        var yDist = y.map(function(p) {
                            return Math.abs(p - cursor[1]);
                        });
                        var dists = xDist.map(function(d, i) {
                            return d + yDist[i];
                        });
                        _this._on[event].bind(_this)(d.arr[dists.indexOf(min(dists))], i, s, e);
                    };
                };
                var _this = this;
                var _pathConfig_on;
                _get(_get_prototype_of(Radar.prototype), "_draw", this).call(this, callback);
                var height = this._height - this._margin.top - this._margin.bottom, width = this._width - this._margin.left - this._margin.right;
                var radius = min([
                    height,
                    width
                ]) / 2 - this._outerPadding, transform = "translate(".concat(width / 2, ", ").concat(height / 2, ")");
                var nestedAxisData = groups(this._filteredData, this._metric), nestedGroupData = groups(this._filteredData, this._id, this._metric);
                var maxValue = max(nestedGroupData.map(function(param) {
                    var _param = _sliced_to_array(param, 2), innerEntries = _param[1];
                    return innerEntries.map(function(param) {
                        var _param = _sliced_to_array(param, 2), vals = _param[1];
                        return sum(vals, function(x, i) {
                            return _this._value(x, i);
                        });
                    });
                }).flat());
                var circularAxis = Array.from(Array(this._levels).keys()).map(function(d) {
                    return {
                        id: d,
                        r: radius * ((d + 1) / _this._levels)
                    };
                });
                var circleConfig = configPrep.bind(this)(this._axisConfig.shapeConfig, "shape", "Circle");
                delete circleConfig.label;
                new Circle().data(circularAxis).select(elem("g.d3plus-Radar-radial-circles", {
                    parent: this._select,
                    enter: {
                        transform: transform
                    },
                    update: {
                        transform: transform
                    }
                }).node()).config(circleConfig).render();
                var totalAxis = nestedAxisData.length;
                var polarAxis = nestedAxisData.map(function(param, i) {
                    var _param = _sliced_to_array(param, 2), key = _param[0], values = _param[1];
                    var d = {
                        key: key,
                        values: values
                    };
                    var width = _this._outerPadding;
                    var fontSize = _this._shapeConfig.labelConfig.fontSize && _this._shapeConfig.labelConfig.fontSize(d, i) || 11;
                    var lineHeight = fontSize * 1.4;
                    var height = lineHeight * 2;
                    var padding = 10, quadrant = parseInt(String(360 - 360 / totalAxis * i / 90), 10) % 4 + 1, radians = tau / totalAxis * i;
                    var angle = 360 / totalAxis * i;
                    var textAnchor = "start";
                    var x = padding;
                    if (quadrant === 2 || quadrant === 3) {
                        x = -width - padding;
                        textAnchor = "end";
                        angle += 180;
                    }
                    var labelBounds = {
                        x: x,
                        y: -height / 2,
                        width: width,
                        height: height
                    };
                    return {
                        __d3plus__: true,
                        data: merge(d.values, _this._aggs),
                        i: i,
                        id: d.key,
                        key: d.key,
                        angle: angle,
                        textAnchor: textAnchor,
                        labelBounds: labelBounds,
                        rotateAnchor: [
                            -x,
                            height / 2
                        ],
                        x: radius * Math.cos(radians),
                        y: radius * Math.sin(radians)
                    };
                }).sort(function(a, b) {
                    return a.key - b.key;
                });
                new Rect().data(polarAxis).rotate(function(d) {
                    return d.angle || 0;
                }).width(0).height(0).x(function(d) {
                    return d.x;
                }).y(function(d) {
                    return d.y;
                }).label(function(d) {
                    return d.id;
                }).labelBounds(function(d) {
                    return d.labelBounds;
                }).labelConfig(this._axisConfig.shapeConfig.labelConfig).select(elem("g.d3plus-Radar-text", {
                    parent: this._select,
                    enter: {
                        transform: transform
                    },
                    update: {
                        transform: transform
                    }
                }).node()).render();
                new Path().data(polarAxis).d(function(d) {
                    return "M".concat(0, ",", 0, " ").concat(-d.x, ",").concat(-d.y);
                }).select(elem("g.d3plus-Radar-axis", {
                    parent: this._select,
                    enter: {
                        transform: transform
                    },
                    update: {
                        transform: transform
                    }
                }).node()).config(configPrep.bind(this)(this._axisConfig.shapeConfig, "shape", "Path")).render();
                var groupData = nestedGroupData.map(function(param) {
                    var _param = _sliced_to_array(param, 2), hKey = _param[0], innerEntries = _param[1];
                    var q = innerEntries.map(function(param, i) {
                        var _param = _sliced_to_array(param, 2), vals = _param[1];
                        var value = sum(vals, function(x, i) {
                            return _this._value(x, i);
                        });
                        var r = value / maxValue * radius, radians = tau / totalAxis * i;
                        return {
                            x: r * Math.cos(radians),
                            y: r * Math.sin(radians)
                        };
                    });
                    var pathD = "M ".concat(q[0].x, " ").concat(q[0].y, " ").concat(q.map(function(l) {
                        return "L ".concat(l.x, " ").concat(l.y);
                    }).join(" "), " L ").concat(q[0].x, " ").concat(q[0].y);
                    return {
                        arr: innerEntries.map(function(param) {
                            var _param = _sliced_to_array(param, 2), vals = _param[1];
                            return merge(vals, _this._aggs);
                        }),
                        id: hKey,
                        points: q,
                        d: pathD,
                        __d3plus__: true,
                        data: merge(innerEntries.map(function(param) {
                            var _param = _sliced_to_array(param, 2), vals = _param[1];
                            return merge(vals, _this._aggs);
                        }), _this._aggs)
                    };
                });
                var pathConfig = configPrep.bind(this)(this._shapeConfig, "shape", "Path");
                var events = Object.keys((_pathConfig_on = pathConfig.on) !== null && _pathConfig_on !== void 0 ? _pathConfig_on : {});
                pathConfig.on = {};
                for(var e = 0; e < events.length; e++)_loop(e);
                this._shapes.push(new Path().data(groupData).d(function(d) {
                    return d.d;
                }).select(elem("g.d3plus-Radar-items", {
                    parent: this._select,
                    enter: {
                        transform: transform
                    },
                    update: {
                        transform: transform
                    }
                }).node()).config(pathConfig).render());
                return this;
            }
        },
        {
            /**
      Configuration object for the radial spokes, circles, and labels.
*/ key: "axisConfig",
            value: function axisConfig(_) {
                return arguments.length ? (this._axisConfig = assign(this._axisConfig, _), this) : this._axisConfig;
            }
        },
        {
            /**
      Accessor function for the metric value used as each axis.
*/ key: "metric",
            value: function metric(_) {
                return arguments.length ? (this._metric = typeof _ === "function" ? _ : accessor(_), this) : this._metric;
            }
        },
        {
            /**
      Determines how much pixel spaces to give the outer labels.
*/ key: "outerPadding",
            value: function outerPadding(_) {
                return arguments.length ? (this._outerPadding = _, this) : this._outerPadding;
            }
        },
        {
            /**
      The value accessor used to determine each data point's position along each axis.

@example
function value(d) {
  return d.value;
}
*/ key: "value",
            value: function value(_) {
                return arguments.length ? (this._value = typeof _ === "function" ? _ : accessor(_), this) : this._value;
            }
        }
    ]);
    return Radar;
}(Viz);
/**
    Creates a radar visualization based on an array of data.
*/ export { Radar as default };
