import { r as registerInstance, h, g as getElement, H as Host } from './index-090d31ca.js';
import { I as InteractingEntryGenerator, s as select, B as BaseDrawer, p as pie, a as BaseChart, L as LayoutInputProcessor, P as ProcessorChain, b as LegendInputProcessor, c as LegendDrawer } from './legend-input-processor-122008c5.js';
import { s as sanitizeVegaComponent } from './component-7d906393.js';
import { I as InjectVegaSlimmer } from './global-slimmer-registry-17c4efd4.js';
import { V as VegaComponentUsageRuntimeMetricsSlimmer, I as InjectVegaGlobalSlimmer } from './component-usage-runtime-metrics-46020a03.js';
import './array-7888f339.js';
import './number-4398f2e1.js';
import './typography-396de03f.js';
import './pixel-f32c07ce.js';

/** The `ArcPathHoverGenerator` class is a TypeScript function that handles mouseover events on SVG elements with a specific class and modifies their appearance. */
class ArcPathHoverGenerator extends InteractingEntryGenerator {
  constructor() {
    super(...arguments);
    this.eventType = 'mouseover';
  }
  /**
   * The function "createShouldHandle" returns a function that takes an event as a parameter and returns a boolean value.
   *
   * @returns {InteractingEntry['shouldHandle']} A function that takes an event as an argument and returns a boolean value.
   */
  createShouldHandle() {
    return this.shouldHandle;
  }
  /**
   * The function "createHandle" returns the handle property of an InteractingEntry object.
   *
   * @returns {InteractingEntry['handle']} The `handle` property of the `InteractingEntry` object is being returned.
   */
  createHandle() {
    return this.handle;
  }
  /**
   * The function checks if the target element of a mouse event has a specific class.
   *
   * @param {MouseEvent} event - MouseEvent is a type of event that is triggered when a mouse action
   * occurs, such as a click or hover. It contains information about the event, such as the target
   * element and the position of the mouse. In this code snippet, the function `shouldHandle` takes in a
   * MouseEvent as a parameter.
   * @returns {boolean} The function `shouldHandle` is returning a boolean value. It checks if the `event.target`
   * is an HTML element with the class name `vega-chart-arc-path`. If it is, then it returns `true`,
   * otherwise it returns `false`.
   */
  shouldHandle(event) {
    return event.target.classList.contains('vega-chart-arc-path');
  }
  /**
   * This function handles mouse events on a D3 selection of SVG elements, specifically for hovering over and highlighting a specific path element.
   *
   * @param {MouseEvent} event - The event parameter is of type MouseEvent, which is an object that
   * contains information about a mouse event, such as the type of event (click, hover, etc.), the
   * target element that triggered the event, and the position of the mouse cursor.
   */
  handle(event) {
    const svgSelection = select(event.currentTarget);
    const targetPathNode = event.target;
    const name = targetPathNode.dataset.name;
    svgSelection.selectAll('.vega-chart-arc-path').each(function () {
      const pathNode = this;
      if (pathNode !== targetPathNode && pathNode.classList.contains('hover')) {
        pathNode.classList.remove('hover');
        const oldPath = pathNode.getAttribute('d');
        const newPath = pathNode.dataset.d;
        pathNode.dataset.d = oldPath;
        select(this).transition(100).duration(100).attr('d', newPath);
      }
      else if (!targetPathNode.classList.contains('hover')) {
        targetPathNode.classList.add('hover');
        const oldPath = targetPathNode.getAttribute('d');
        const newPath = targetPathNode.dataset.d;
        targetPathNode.dataset.d = oldPath;
        select(targetPathNode).transition(100).duration(100).attr('d', newPath);
        svgSelection.select('.vega-chart-draw-g text').text(name);
      }
    });
  }
}

/** The PathDrawer class draws a path on a chart using provided data and color options. */
class ArcPathDrawer extends BaseDrawer {
  constructor() {
    super(...arguments);
    this.arcPathHoverEntryGenerator = new ArcPathHoverGenerator();
  }
  /**
   * This function adds interaction support to a given drawPiece using an interactor and an arcPathHoverEntryGenerator.
   *
   * @param {(SVGPathElement | HTMLCanvasElement)[]} drawPiece - drawPiece is an array of SVGPathElement
   * or HTMLCanvasElement objects that represent the pieces to be drawn on the screen. These elements
   * are used to render the game board and interact with the user. The addInteractionSupport method
   * registers the current object as an interactive element with the interactor
   */
  addInteractionSupport(drawPiece) {
    this.interactor.register(this, drawPiece, this.arcPathHoverEntryGenerator.generate());
  }
  /**
   * This function draws a chart with arcs using data and options provided, and returns an array of SVGPathElement or HTMLCanvasElement.
   *
   * @returns {(SVGPathElement | HTMLCanvasElement)[]} An array of either SVGPathElement or HTMLCanvasElement, depending on the result of the map function.
   */
  draw() {
    const { data, colors, donutRadius, outerRadius, center } = this.options.renderOptions;
    return data.map((item, index) => {
      const color = this.getColorFromToken(this.getColorByIndex(index, colors));
      return this.renderer.drawArcPath(center, item, color, outerRadius, donutRadius);
    });
  }
}

/** The TextDrawer class draws a text on a chart using provided options. */
class TextDrawer extends BaseDrawer {
  /** This function adds interaction support */
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  addInteractionSupport() { }
  /**
   * This function draws a text on a chart using specified options.
   */
  draw() {
    const options = this.options.renderOptions;
    options.forEach((item) => {
      const { position, text, styleToken, textAnchor, rotate } = item;
      this.renderer.drawText(position, text, this.getStyleTextFromToken(styleToken), textAnchor, rotate);
    });
  }
}

/** The PieChartArchPathInputProcessor class processes input data to generate options for rendering a pie or donut chart with D3.js. */
class PieChartArchPathInputProcessor {
  /**
   * This function processes input data to generate options for rendering a pie or donut chart with D3.js.
   *
   * @param {ChartOptions<PieChartSourceType>} input - The input parameter is an object containing chart options, including the data source, colors, layout, donut radius, and type of chart.
   * @param {PieChartRadiusProcessResultType} previousOutput - previous result from the other input process
   * @returns {ChartArcOptions} An object with a property `renderOptions` which contains an object with properties `data`,
   * `colors`, `outerRadius`, `donutRadius`, and `center`.
   */
  process(input, previousOutput) {
    const { dataSource: filterDataSource, colors } = input;
    const { radius, innerRadius, center } = previousOutput;
    const renderData = pie().value((d) => d.value)(filterDataSource);
    return {
      data: renderData,
      colors,
      outerRadius: radius,
      donutRadius: innerRadius,
      center,
    };
  }
}

/** The PieChartArchPathInputProcessor class processes input data to generate options for rendering a pie or donut chart with D3.js. */
class PieChartTextInputProcessor {
  /**
   * This function processes input data to generate options for rendering a pie or donut chart with D3.js.
   *
   * @param {ChartArcOptions} input - chartArcPathInputProcessor process result
   * @returns {TextInputType[]} An object with a property `renderOptions` which contains an object with properties `data`,
   * `colors`, `outerRadius`, `donutRadius`, and `center`.
   */
  process(input) {
    const { center } = input;
    const textArray = [
      {
        text: '',
        position: center,
        textAnchor: 'middle',
        styleToken: 'v-font-footnote2-short',
      },
    ];
    return textArray;
  }
}

/** The PieChartFilterInputProcessor class filters out any items in the input dataSource that do not have a name and value property for a pie chart. */
class PieChartFilterInputProcessor {
  /**
   * This function filters out any items in the input dataSource that do not have a name and value property.
   *
   * @param {ChartOptions<PieChartSourceType>} input - The input parameter is of type ChartOptions<PieChartSourceType>, which is an object
   * containing options for a pie chart. It includes properties such as the chart title, data source,
   * and chart configuration options. The function is designed to filter out any data items in the data
   * source that do not have a name or value
   * @returns {ChartOptions<PieChartSourceType>} the modified input object of type `ChartOptions<PieChartSourceType>`.
   */
  process(input) {
    const filterDataSource = input.dataSource.filter((item) => !!(item.name && item.value));
    input.dataSource = filterDataSource;
    return input;
  }
}

/** The PieChartRadiusInputProcessor class calculates the radius, inner radius, and center of a pie chart based on input options and previous layout results. */
class PieChartRadiusInputProcessor {
  /**
   * This function calculates the radius and center position of a pie chart based on input options and previous layout results.
   *
   * @param {ChartOptions<PieChartSourceType>} input - An object of type ChartOptions that contains options for the pie chart, including
   * the type of chart (either "Pie" or "Donut") and the donut radius (a number between 0 and 1 that
   * determines the size of the hole in the center of a donut chart).
   * @param {LayoutProcessResultType} previousOutput - The `previousOutput` parameter is of type
   * `LayoutProcessResultType` and represents the output of the previous layout process. It contains
   * information about the inner width and height of the chart area, which is used to calculate the
   * radius and center of the pie chart.
   * @returns {PieChartRadiusProcessResultType} an object of type `PieChartRadiusProcessResultType` which contains the `radius`,
   * `innerRadius`, and `center` properties.
   */
  process(input, previousOutput) {
    const { type, donutRadius } = input;
    const { innerWidth, innerHeight } = previousOutput;
    const radius = Math.min(innerWidth, innerHeight) / 2;
    const innerRadius = type === 'Donut' ? (!donutRadius || donutRadius <= 0 ? 0.6 : Math.min(donutRadius, 0.9)) : 0;
    // left pie chart, right legend center should be x: innerWidth/4, the top legend, bottom chart center should be x: innerWidth/2
    const center = {
      x: innerWidth / 2,
      y: innerHeight / 2,
    };
    return { radius, innerRadius: innerRadius * radius, center };
  }
}

/**
 * The PieChart class is a TypeScript implementation of a pie chart that extends the BaseChart class
 * and includes methods for creating a drawer chain
 */
class PieChart extends BaseChart {
  constructor() {
    super(...arguments);
    this.layoutInputProcessor = new LayoutInputProcessor();
    this.filterInputProcessor = new PieChartFilterInputProcessor();
    this.radiusInputProcessor = new PieChartRadiusInputProcessor();
    this.arcPathInputProcessorChain = new ProcessorChain([
      this.filterInputProcessor,
      this.layoutInputProcessor,
      this.radiusInputProcessor,
      new PieChartArchPathInputProcessor(),
    ]);
    this.textInputProcessor = new PieChartTextInputProcessor();
    this.legendInputProcessChain = new ProcessorChain([
      this.layoutInputProcessor,
      new LegendInputProcessor(),
    ]);
  }
  /**
   * This function creates an array of BaseDrawer objects for rendering a chart with legends, and paths.
   *
   * @param {BaseRenderer<SVGElement | HTMLCanvasElement>} renderer - an instance of a BaseRenderer class that can render SVG or Canvas elements.
   * @param {BaseInteractor<SVGElement | HTMLCanvasElement>} interactor - an instance of a BaseInteractor class
   * @returns {BaseDrawer<unknown>[]} An array of BaseDrawer array.
   */
  createDrawerChain(renderer, interactor) {
    const arcPathProcessorChainOutput = this.arcPathInputProcessorChain.process(this.options);
    const legendInputProcessChainOutput = this.legendInputProcessChain.process(this.options);
    return [
      new ArcPathDrawer(renderer, interactor, {
        renderOptions: arcPathProcessorChainOutput,
      }),
      new TextDrawer(renderer, interactor, {
        renderOptions: this.textInputProcessor.process(arcPathProcessorChainOutput),
      }),
      new LegendDrawer(renderer, interactor, {
        renderOptions: legendInputProcessChainOutput,
      }),
    ];
  }
}

const vegaPieChartCss = ".vega-chart-legend-item{cursor:pointer}.vega-chart-line-path:hover{stroke-width:5}:host{display:block}";

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __rest = (undefined && undefined.__rest) || function (s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
const VegaPieChart = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.globalSlimmers = {};
    this.vegaComponentUsageRuntimeMetricsSlimmer = new VegaComponentUsageRuntimeMetricsSlimmer();
  }
  watchOptionsHandel(options) {
    this.updateChart(options);
  }
  disconnectedCallback() {
    this.chart = null;
    this.reRenderTimer && clearTimeout(this.reRenderTimer);
  }
  componentWillLoad() {
    this.updateChart(this.options);
  }
  /**
   * Invoke this method to render the chart using the existing options.
   *    If the chart is displayed incorrectly within a modal or tab,
   *    ensure that this method is invoked after the chart is shown
   *    to ensure proper rendering.
   *
   * @vegaVersion 1.35.0
   */
  async reRender() {
    this.reRenderTimer && clearTimeout(this.reRenderTimer);
    /* istanbul ignore next */
    this.reRenderTimer = setTimeout(() => {
      this.chart.reRender();
    }, 0);
  }
  render() {
    return sanitizeVegaComponent(h(Host, null), this.host);
  }
  /**
   * This function draws a pie chart using the provided options and data source.
   *
   * @param {PieChartOptions} options - The options parameter is an object that contains various options for configuring and rendering a line chart.
   */
  updateChart(options) {
    if (!options)
      return;
    const { mode = 'svg', dataSource } = options, restOptions = __rest(options, ["mode", "dataSource"]);
    const mergedOptions = Object.assign(Object.assign({}, restOptions), { mode, container: this.host, dataSource: dataSource || [] });
    if (this.chart) {
      this.chart.updateOptions(mergedOptions);
    }
    else {
      this.chart = new PieChart(mergedOptions);
      this.chart.render();
    }
  }
  get host() { return getElement(this); }
  static get watchers() { return {
    "options": ["watchOptionsHandel"]
  }; }
};
__decorate([
  InjectVegaGlobalSlimmer()
], VegaPieChart.prototype, "globalSlimmers", void 0);
__decorate([
  InjectVegaSlimmer()
], VegaPieChart.prototype, "vegaComponentUsageRuntimeMetricsSlimmer", void 0);
VegaPieChart.style = vegaPieChartCss;

export { VegaPieChart as vega_pie_chart };
