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_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(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(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread 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 _super_prop_base(object, property) {
    while(!Object.prototype.hasOwnProperty.call(object, property)){
        object = _get_prototype_of(object);
        if (object === null) break;
    }
    return object;
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
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 { hierarchy, pack } from "d3-hierarchy";
import { assign, elem } from "@d3plus/dom";
import { nestGroups } from "@d3plus/data";
import { accessor, configPrep, constant } from "../utils/index.js";
import { Circle } from "../shapes/index.js";
import Viz from "./Viz.js";
var recursionCircles = function recursionCircles1(d) {
    var arr = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
    if (d.values) {
        d.values.forEach(function(h) {
            arr.push(h);
            recursionCircles(h, arr);
        });
    } else {
        arr.push(d);
    }
    return arr;
};
var Pack = /*#__PURE__*/ function(Viz) {
    "use strict";
    _inherits(Pack, Viz);
    function Pack() {
        _class_call_check(this, Pack);
        var _this;
        _this = _call_super(this, Pack);
        _this._layoutPadding = 1;
        var defaultLegend = _this._legend;
        _this._legend = function(config, arr) {
            if (arr.length === _this._filteredData.length) return false;
            return defaultLegend.bind(_this)(config, arr);
        };
        _this._on.mouseenter = function() {};
        var defaultMouseMoveLegend = _this._on["mousemove.legend"];
        _this._on["mousemove.legend"] = function(d, i, x, event) {
            defaultMouseMoveLegend(d, i, x, event);
            var ids = _this._ids(d, i);
            var hoverData = recursionCircles(d);
            _this.hover(function(h) {
                var _hoverData;
                var hover = Object.keys(h).filter(function(key) {
                    return key !== "value";
                }).every(function(key) {
                    return d[key] && d[key].includes(h[key]);
                });
                if (hover) hoverData.push(h);
                else if (ids.includes(h.key)) (_hoverData = hoverData).push.apply(_hoverData, _to_consumable_array(recursionCircles(h, [
                    h
                ])));
                return hoverData.includes(h);
            });
        };
        var defaultMouseMoveShape = _this._on["mousemove.shape"];
        _this._on["mousemove.shape"] = function(d, i, x, event) {
            if (d.__d3plusTooltip__) defaultMouseMoveShape(d, i, x, event);
            var hoverData = recursionCircles(d, [
                d
            ]);
            _this.hover(function(h) {
                return hoverData.includes(h);
            });
        };
        _this._pack = pack();
        _this._packOpacity = constant(0.25);
        _this._shape = constant("Circle");
        _this._shapeConfig = assign(_this._shapeConfig, {
            Circle: {
                label: function label(d) {
                    return d.parent && !d.children ? d.id : false;
                },
                labelConfig: {
                    fontResize: true
                },
                opacity: function opacity(d) {
                    return d.__d3plusOpacity__;
                }
            }
        });
        _this._sort = function(a, b) {
            return b.value - a.value;
        };
        _this._sum = accessor("value");
        return _this;
    }
    _create_class(Pack, [
        {
            /**
      Extends the draw behavior of the abstract Viz class.
      @private
*/ key: "_draw",
            value: function _draw(callback) {
                var _this = this;
                _get(_get_prototype_of(Pack.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 diameter = Math.min(height, width);
                var transform = "translate(".concat((width - diameter) / 2, ", ").concat((height - diameter) / 2, ")");
                var nestedData = nestGroups(this._filteredData, this._groupBy.slice(0, this._drawDepth + 1));
                var packData = this._pack.padding(this._layoutPadding).size([
                    diameter,
                    diameter
                ])(hierarchy({
                    key: nestedData.key,
                    values: nestedData
                }, function(d) {
                    return d.values;
                }).sum(this._sum).sort(this._sort)).descendants().filter(function(d, i) {
                    d.__d3plus__ = true;
                    d.i = i;
                    d.id = d.parent ? d.parent.data.key : "root";
                    d.data.__d3plusOpacity__ = d.height ? _this._packOpacity(d.data, i) : 1;
                    d.data.__d3plusTooltip__ = !d.height ? true : false;
                    return !d.children || d.children.length > 1;
                });
                this._shapes.push(new Circle().data(packData).select(elem("g.d3plus-Pack", {
                    parent: this._select,
                    enter: {
                        transform: transform
                    },
                    update: {
                        transform: transform
                    }
                }).node()).config(configPrep.bind(this)(this._shapeConfig, "shape", "Circle")).render());
                return this;
            }
        },
        {
            /**
      The hover callback function for highlighting shapes on mouseover.
*/ key: "hover",
            value: function hover(_) {
                this._hover = _;
                this._shapes.forEach(function(s) {
                    return s.hover(_);
                });
                if (this._legend) this._legendClass.hover(_);
                return this;
            }
        },
        {
            /**
      The inner and outer padding for the pack layout.
*/ key: "layoutPadding",
            value: function layoutPadding(_) {
                return arguments.length ? (this._layoutPadding = _, this) : this._layoutPadding;
            }
        },
        {
            /**
      The opacity of nested circles within the pack layout.
*/ key: "packOpacity",
            value: function packOpacity(_) {
                return arguments.length ? (this._packOpacity = typeof _ === "function" ? _ : constant(_), this) : this._packOpacity;
            }
        },
        {
            /**
      Sort comparator function for the pack layout. Defaults to descending order by the associated input data's numeric value attribute.

@example
function comparator(a, b) {
  return b.value - a.value;
}
*/ key: "sort",
            value: function sort(_) {
                return arguments.length ? (this._sort = _, this) : this._sort;
            }
        },
        {
            /**
      The sum accessor used for sizing each circle in the pack layout.

@example
function sum(d) {
  return d.sum;
}
*/ key: "sum",
            value: function sum(_) {
                return arguments.length ? (this._sum = typeof _ === "function" ? _ : accessor(_), this) : this._sum;
            }
        }
    ]);
    return Pack;
}(Viz);
/**
    Uses the [d3 pack layout](https://github.com/d3/d3-hierarchy#pack) to creates Circle Packing chart based on an array of data.
*/ export { Pack as default };
